﻿using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shell;
using System.Windows.Threading;
using CommunityToolkit.Mvvm.Messaging;
using DynamicData;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Xaml.Behaviors;
using Serilog;
using SimpleTool.ActivityUnit;
using SimpleTool.Base;
using SimpleTool.SerialTool.SerialControl;
using SimpleTool.Server;
using Supabase.Postgrest.Attributes;
using static SimpleTool.SerialTool.SerialControl.CommandSectionModel;
using static SimpleTool.Server.Extendsion;

namespace SimpleTool.TransformComponent
{
    /// <summary>
    /// <para> 当前自定义 Window 类中，Content 已被弃用，请使用 MainContent 来进行布局</para>
    /// </summary>
    [ContentProperty("MainContent")]
    public class EnjoyWindow : Window
    {
        private readonly ILogger Logger = Log.ForContext<EnjoyWindow>();

        private readonly Border MainGlobalBorder;

        private readonly Border MainContentBorder;

        private ItemsControl? TaskBar;

        private ICommand? CmdMoveStdin;

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [Obsolete("请使用 MainContent 属性来设置内容区域，Content 属性已被禁用", true)]
        private new object Content
        {
            get => base.Content;
            set
            {
                throw new InvalidOperationException("请使用当前自定义类的 [mainContent] 来进行布局，而不是 Content");
            }
        }
   
        public UIElement MainContent
        {
            set
            {
                this.Dispatcher.Invoke(() =>
                {
                    SetValue(MainContentProperty, value);
                });
            }

            get => (UIElement)GetValue(MainContentProperty);
        }

        public CornerRadius CornerRadius
        {
            set => SetValue(CornerRadiusProperty, value);

            get => (CornerRadius)GetValue(CornerRadiusProperty);
        }

        public string TitleNamed
        {
            set => SetValue(TitleNamedProperty, value);

            get => (string)GetValue(TitleNamedProperty);
        }

        public string TitleIcon
        {
            set => SetValue(TitleIconProperty, value);

            get => (string)GetValue(TitleIconProperty);
        }

        public new Brush BorderBrush
        {
            set => SetValue(BorderBrushProperty, value);
            get => (Brush)GetValue(BorderBrushProperty);
        }

        public new Thickness BorderThickness
        {
            set => SetValue(BorderThicknessProperty, value);
            get => (Thickness)GetValue(BorderThicknessProperty);
        }

        public ICollection<TopMenuOptions> ItemsSource
        {
            set
            {
                SetValue(ItemsSourceProperty, value);
            }
            get
            {
                return (ICollection<TopMenuOptions>)GetValue(ItemsSourceProperty);
            }
        }

        private static readonly DependencyProperty MainContentProperty = DependencyProperty.Register(
            nameof(MainContent),
            typeof(UIElement),
            typeof(EnjoyWindow),
            new PropertyMetadata(null, BorderContentChangeEvent));

        private static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
             nameof(CornerRadius),
             typeof(CornerRadius),
             typeof(EnjoyWindow),
             new PropertyMetadata(new CornerRadius(12)));

        private static readonly DependencyProperty TitleNamedProperty = DependencyProperty.Register(
            nameof(TitleNamed),
            typeof(string),
            typeof(EnjoyWindow),
            new PropertyMetadata(string.Empty, TitleNamedChangeEvent));

        private static readonly DependencyProperty TitleIconProperty = DependencyProperty.Register(
            nameof(TitleIcon),
            typeof(string),
            typeof(EnjoyWindow),
            new PropertyMetadata(string.Empty, TitleIconChangeEvent));

        private static readonly new DependencyProperty BorderBrushProperty = DependencyProperty.Register(
            nameof(BorderBrush),
            typeof(Brush),
            typeof(EnjoyWindow),
            new PropertyMetadata("CoralRed".FindSolidBrush(), BorderBrushChangeEvent));

        private static readonly new DependencyProperty BorderThicknessProperty = DependencyProperty.Register(
            nameof(BorderThickness),
            typeof(Thickness),
            typeof(EnjoyWindow),
            new PropertyMetadata(new Thickness(3), BorderThicknessChangeEvent));

        private static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
             nameof(ItemsSource),
             typeof(ICollection<TopMenuOptions>),
             typeof(EnjoyWindow),
             new PropertyMetadata(ItemsSourceChangeEvent));

        public static void BorderContentChangeEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is EnjoyWindow window && e.NewValue is UIElement Layout)
            {
                window.Dispatcher.Invoke(() =>
                {
                    window.MainContentBorder.Child = Layout;
                });
            }
        }

        public static void TitleNamedChangeEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is EnjoyWindow Self)
            {
                Self.Dispatcher.Invoke(async () =>
                {
                    object? Component = await Server.Visual.GetVisual<EnjoyWindow, TextBlock>(Self, new Server.Visual.VisualArg
                    {
                        SourceNames = [nameof(TitleNamed)],
                        GetFirst = true,
                        Orient = Server.Visual.VisualOrient.Bottom
                    });

                    if (Component is not null and TextBlock TitleNamedComponent &&
                        e.NewValue is string TitleName)
                    {
                        TitleNamedComponent.Text = TitleName;
                    }
                });
            }
        }

        public static void TitleIconChangeEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is EnjoyWindow Self)
            {
                Self.Dispatcher.Invoke(async () =>
                {
                    object? Component = await Server.Visual.GetVisual<EnjoyWindow, TextBlock>(Self, new Server.Visual.VisualArg
                    {
                        SourceNames = [nameof(TitleIcon)],
                        GetFirst = true,
                        Orient = Server.Visual.VisualOrient.Bottom
                    });

                    if (Component is not null and TextBlock TitleIconComponent &&
                        e.NewValue is string TitleIcond)
                    {
                        TitleIconComponent.Text = TitleIcond;
                    }
                });
            }
        }

        private static void BorderBrushChangeEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is EnjoyWindow Self && e.NewValue is Brush BorderBrush)
            {
                Self.Dispatcher.Invoke(() =>
                {
                    Self.MainGlobalBorder.BorderBrush = BorderBrush;
                });
            }
        }

        private static void BorderThicknessChangeEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is EnjoyWindow Self && e.NewValue is Thickness BorderThickness)
            {
                Self.Dispatcher.Invoke(() =>
                {
                    Self.MainGlobalBorder.BorderThickness = BorderThickness;
                });
            }
        }

        private static void ItemsSourceChangeEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is EnjoyWindow Self)
            {
                if (e.NewValue is IEnumerable Items &&
                    Self.TaskBar is not null)
                {
                    Self.TaskBar.ItemsSource = Items;
                }
            }
        }

        public EnjoyWindow()
        {
            WindowStyle = WindowStyle.None;
            Background = Brushes.Transparent;
            AllowsTransparency = true;
            Margin = new Thickness(0);
            Padding = new Thickness(0);
            Opacity = 0;
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            Height = 705;
            Width = 1250;

            WindowChrome EnjotWindowChorme = new ()
            {
                CaptionHeight = 0, 
                CornerRadius = new CornerRadius(0), 
                GlassFrameThickness = new Thickness(-1), 
                ResizeBorderThickness = new Thickness(2)
            };

            WindowChrome.SetWindowChrome(this, EnjotWindowChorme);

            MainGlobalBorder = new ()
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                ClipToBounds = true,
                CornerRadius = CornerRadius,
                BorderBrush = BorderBrush,
                BorderThickness = BorderThickness
            };

            var MainGrid = new Grid() { Name = "MainGrid" };
            MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(35) });
            MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(5, GridUnitType.Star) });

            LinearGradientBrush BackGradient = new()
            {
                StartPoint = new Point(0.3, 0),

                EndPoint = new Point(0.4, 1)
            };
            BackGradient.GradientStops.Add(new GradientStop("#FDF6E3".GetColor(), 0.1));
            BackGradient.GradientStops.Add(new GradientStop("#FEF8F5".GetColor(), 0.5));
            BackGradient.GradientStops.Add(new GradientStop("#FDF6E3".GetColor(), 0.7));

            MainGlobalBorder.Background = BackGradient;

            MainContentBorder = new Border() { Background = Brushes.Transparent };

            MainGrid.SetGridWidget(0, 0, CaptionBar());
            MainGrid.SetGridWidget(1, 0, MainContentBorder);

            MainGlobalBorder.Child = MainGrid;

            base.Content = MainGlobalBorder;

            WeakEventManager<EnjoyWindow, RoutedEventArgs>.AddHandler(this, nameof(Loaded), WeakLoadedEvent);
        }

        public Border CaptionBar()
        {
            var TitleGrid = new Grid();
            TitleGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(35) });
            TitleGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            TitleGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            TitleGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(130) });

            // 创建标题栏 Border
            var TitleBar = new Border
            {
                BorderThickness = new Thickness(0, 0, 0, 1),
                BorderBrush = (Brush)Application.Current.FindResource("FrostedSlate"),
                Background = Brushes.Transparent,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                Margin = new Thickness(0),
                Padding = new Thickness(0),
                ClipToBounds = true
            };

            // 图标 TextBlock
            var IconTextBlock = new TextBlock
            {
                Text = TitleIcon, // &#xe61a; 的 C# 字符串表示
                FontFamily = "Icon".FindSource<FontFamily>(),
                FontSize = 24,
                Name = nameof(TitleIcon),
                FontWeight = FontWeights.Medium,
                Foreground = "GaoguiZong".FindSolidBrush(),
                Background = Brushes.Transparent,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            // 标题文字 TextBlock
            var TitleTextBlock = new TextBlock
            {
                Text = TitleNamed,
                FontFamily = "YaHei".FindSource<FontFamily>(),
                FontSize = 17,
                Name = nameof(TitleNamed),
                Foreground = "GaoguiZong".FindSolidBrush(),
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = new Thickness(8, 0, 0, 0) // 图标和文字间距 8
            };

            var uniformGrid = new UniformGrid
            {
                Background = Brushes.Transparent,
                Columns = 3,
                Width = 130,
                HorizontalAlignment = HorizontalAlignment.Right
            };

            // Green button
            var NormalButtom = new VariantButton
            {
                Height = 26,
                Width = 26,
                CornerRadius = new CornerRadius(14),
                BorderThickness = new Thickness(2),
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#28C840")),
                BorderBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#28C840")),
                MouseHoverBgColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#28C840")),
                MouseHoverBdColor = (Brush)Application.Current.FindResource("DeepWhite"),
                MousePreeBgColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#28C840")),
                MousePreeBdColor = (Brush)Application.Current.FindResource("DeepWhite"),
                FontSize = 14
            };


            // Yellow button
            var MinButtom = new VariantButton
            {
                Height = 26,
                Width = 26,
                CornerRadius = new CornerRadius(14),
                BorderThickness = new Thickness(2),
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBD2E")),
                BorderBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBD2E")),
                MouseHoverBgColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBD2E")),
                MouseHoverBdColor = (Brush)Application.Current.FindResource("DeepWhite"),
                MousePreeBgColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBD2E")),
                MousePreeBdColor = (Brush)Application.Current.FindResource("DeepWhite"),
                FontSize = 14
            };

            // Red button
            var CloseButtom = new VariantButton
            {
                Height = 26,
                Width = 26,
                CornerRadius = new CornerRadius(14),
                BorderThickness = new Thickness(2),
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF5F5F")),
                BorderBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF5F5F")),
                MouseHoverBgColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF5F5F")),
                MouseHoverBdColor = (Brush)Application.Current.FindResource("DeepWhite"),
                MousePreeBgColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF5F5F")),
                MousePreeBdColor = (Brush)Application.Current.FindResource("DeepWhite"),
                FontSize = 14
            };

            WeakEventManager<VariantButton, MouseButtonEventArgs>.AddHandler(NormalButtom, nameof(VariantButton.PreviewMouseUp), NormalFuncEvent);
            WeakEventManager<VariantButton, MouseButtonEventArgs>.AddHandler(MinButtom, nameof(VariantButton.PreviewMouseUp), MinFuncEvent);
            WeakEventManager<VariantButton, MouseButtonEventArgs>.AddHandler(CloseButtom, nameof(VariantButton.PreviewMouseUp), CloseFuncEvent);

            uniformGrid.Children.Add(NormalButtom);
            uniformGrid.Children.Add(MinButtom);
            uniformGrid.Children.Add(CloseButtom);

            TaskBar = new()
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Center,
                Background = Brushes.Transparent,
                Style = "TopMenuItems".FindSource<Style>()
            };

            TitleGrid.SetGridWidget(0, 0, IconTextBlock);
            TitleGrid.SetGridWidget(0, 1, TitleTextBlock);
            TitleGrid.SetGridWidget(0, 2, TaskBar);
            TitleGrid.SetGridWidget(0, 3, uniformGrid);

            TitleBar.Child = TitleGrid;

            Server.Behavior Mybehavior = new()
            {
                CmdLeftKeyClick = CmdMove
            };

            Interaction.GetBehaviors(TitleBar).Add(Mybehavior);

            return TitleBar;
        }

        public ICommand CmdMove
        {
            set
            {
                CmdMoveStdin = value;
            }
            get
            {
                CmdMoveStdin ??= new EasyCommand((obj) => { DragMove(); }, bool () => { return true; });
                return CmdMoveStdin;
            }
        }

        public async void NormalFuncEvent(object? sender, MouseButtonEventArgs e)
        {
            if (sender is not null and VariantButton _Buttom)
            {
                await _Buttom.Dispatcher.Invoke(async () =>
                {
                    object? MainWindow = await Server.Visual.GetVisual<EnjoyWindow>(_Buttom, new Server.Visual.VisualArg()
                    {
                        Orient = Server.Visual.VisualOrient.Top,
                        GetFirst = true
                    });

                    if (MainWindow is not null and EnjoyWindow Self)
                    {
                        if (Self.WindowState == WindowState.Normal)
                        {
                            Self.WindowState = WindowState.Maximized;
                        }
                        else
                        {
                            Self.WindowState = WindowState.Normal;
                        }
                    }
                });
            }
        }

        public async void MinFuncEvent(object? sender, MouseButtonEventArgs e)
        {
            if (sender is not null and VariantButton _Buttom)
            {
                await _Buttom.Dispatcher.Invoke(async () =>
                {
                    object? MainWindow = await Server.Visual.GetVisual<EnjoyWindow>(_Buttom, new Server.Visual.VisualArg()
                    {
                        Orient = Server.Visual.VisualOrient.Top,
                        GetFirst = true
                    });

                    if (MainWindow is not null and EnjoyWindow Self)
                    {
                        Self.WindowState = WindowState.Minimized;
                    }
                });
            }
        }

        public async void CloseFuncEvent(object? sender, MouseButtonEventArgs e)
        {
            if (sender is not null and VariantButton _Buttom)
            {
                await _Buttom.Dispatcher.Invoke(async () =>
                {
                    object? MainWindow = await Server.Visual.GetVisual<EnjoyWindow>(_Buttom, new Server.Visual.VisualArg()
                    {
                        Orient = Server.Visual.VisualOrient.Top,
                        GetFirst = true
                    });

                    if (MainWindow is not null and EnjoyWindow Self)
                    {
                        Self.Close();
                    }
                });
            }
        }

        public void WeakLoadedEvent(object? sender, RoutedEventArgs e)
        {
            if (sender is not null and EnjoyWindow Self)
            {
                SetClip(Self, Self.ActualWidth, Self.ActualHeight);
            }
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            SetClip(this, ActualWidth, ActualHeight);
            base.OnRenderSizeChanged(sizeInfo);
        }

        public async void SetClip(FrameworkElement Self, double Width, double Height)
        {
            object? Layout = await Server.Visual.GetVisual<Grid>(Self, new Server.Visual.VisualArg
            {
                SourceNames = ["MainGrid"],
                GetFirst = true,
                Orient = Server.Visual.VisualOrient.Bottom
            });

            var clipGeometry = new RectangleGeometry
            {
                RadiusX = 12,
                RadiusY = 12,
                Rect = new Rect(0, 0, Width -1, Height + 1)
            };

            if (Layout is not null and Grid MainGrid)
            {
                MainGrid.Clip = clipGeometry;
            }
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == VisibilityProperty || e.Property == IsVisibleProperty)
            {
                if (Opacity == 0)
                {
                    DoubleAnimation VisibleAnimation = new (1.0, TimeSpan.FromMilliseconds(300));

                    BeginAnimation(OpacityProperty, VisibleAnimation);
                }
            }
            base.OnPropertyChanged(e);
        }
    }

    public class EnjoyBorder : Border
    {
        public EnjoyBorder()
        {
            Opacity = 0.0;

            AnimationFramector(AnimationBegin);
        }

        public double AnimationStartTime
        {
            set
            {
                SetValue(AnimationStartTimeProperty, value);
            }
            get
            {
                return (double)GetValue(AnimationStartTimeProperty);
            }
        }

        public double AnimationEndTime
        {
            set
            {
                SetValue(AnimationEndTimeProperty, value);
            }
            get
            {
                return (double)GetValue(AnimationEndTimeProperty);
            }
        }

        public bool UseDefaultAnimationSetting
        {
            set
            {
                SetValue(UseDefaultAnimationSettingProperty, value);
            }
            get
            {
                return (bool)GetValue(UseDefaultAnimationSettingProperty);
            }
        }

        public bool AnimationBegin
        {
            set
            {
                SetValue(AnimationBeginProperty, value);
            }
            get
            {
                return (bool)GetValue(AnimationBeginProperty);
            }
        }

        public bool EnableAnimationCollapsed
        {
            set
            {
                SetValue(EnableAnimationCollapsedProperty, value);
            }
            get
            {
                return (bool)GetValue(EnableAnimationCollapsedProperty);
            }
        }

        public static readonly DependencyProperty AnimationBeginProperty = DependencyProperty.Register(
            nameof(AnimationBegin),
            typeof(bool),
            typeof(EnjoyBorder),
            new PropertyMetadata(false, AnimationStateChangeEvent));

        public static readonly DependencyProperty UseDefaultAnimationSettingProperty = DependencyProperty.Register(
            nameof(UseDefaultAnimationSetting),
            typeof(bool),
            typeof(EnjoyBorder),
            new PropertyMetadata(false));

        public static readonly DependencyProperty AnimationStartTimeProperty = DependencyProperty.Register(
            nameof(AnimationStartTime),
            typeof(double),
            typeof(EnjoyBorder),
            new PropertyMetadata(300.0));

        public static readonly DependencyProperty AnimationEndTimeProperty = DependencyProperty.Register(
            nameof(AnimationEndTime), 
            typeof(double), 
            typeof(EnjoyBorder), 
            new PropertyMetadata(300.0));

        public static readonly DependencyProperty EnableAnimationCollapsedProperty = DependencyProperty.Register(
            nameof(EnableAnimationCollapsed),
            typeof(bool),
            typeof(EnjoyBorder),
            new PropertyMetadata(false));

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == OpacityProperty)
            {
                if (e.NewValue is double _Opacity)
                {
                    if (_Opacity == 0.0 && EnableAnimationCollapsed)
                    {
                        Visibility = Visibility.Collapsed;
                    }
                }
            }
            base.OnPropertyChanged(e);
        }

        private static void AnimationStateChangeEvent(DependencyObject a, DependencyPropertyChangedEventArgs e)
        {
            if (a is EnjoyBorder self)
            {
                if (e.NewValue is bool _Bool)
                {
                    self.AnimationFramector(_Bool);
                }
            }
        }

        private void AnimationFramector(bool isBegin)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (isBegin)
                {
               
                    Visibility = Visibility.Visible;
                    if (UseDefaultAnimationSetting)
                    {
                        DoubleAnimation VisibleAnimation = new(1.0, new Duration(TimeSpan.FromMilliseconds(AnimationStartTime)));
                        BeginAnimation(OpacityProperty, VisibleAnimation);
                    }
                }
                else
                {
                    if (EnableAnimationCollapsed && UseDefaultAnimationSetting)
                    {
                        DoubleAnimation VisibleAnimation = new(0.0, new Duration(TimeSpan.FromMilliseconds(AnimationEndTime)));
                        BeginAnimation(OpacityProperty, VisibleAnimation);
                    }
                    else
                    {
                        Visibility = Visibility.Collapsed;
                    }
                }
            });
        }
    }

    public class EnjoyTextBox : TextBox
    {

        public readonly ILogger Logger = Log.ForContext<EnjoyTextBox>();

        public Deserted Options
        {
            set
            {
                SetValue(OptionsProperty, value);
            }
            get
            {
                return (Deserted)GetValue(OptionsProperty);
            }
        }


        public CornerRadius CornerRadius
        {
            set
            {
                SetValue(CornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(CornerRadiusProperty);
            }
        }

        public Brush SelectionBGBrush
        {
            set
            {
                SetValue(SelectionBGBrushProperty, value);
            }
            get
            {
                return (Brush)GetValue(SelectionBGBrushProperty);
            }
        }

        public bool CannelIsReadOnly
        {
            set
            {
                SetValue(CannelIsReadOnlyProperty, value);
            }
            get
            {
                return (bool)GetValue(CannelIsReadOnlyProperty);
            }
        }

        public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
            nameof(CornerRadius),
            typeof(CornerRadius),
            typeof(EnjoyTextBox));

        public static readonly DependencyProperty SelectionBGBrushProperty = DependencyProperty.Register(
            nameof(SelectionBGBrush),
            typeof(Brush),
            typeof(EnjoyTextBox),
            new PropertyMetadata(Brushes.Black));

        public static readonly DependencyProperty CannelIsReadOnlyProperty = DependencyProperty.Register(
            nameof(CannelIsReadOnly),
            typeof(bool),
            typeof(EnjoyTextBox),
            new PropertyMetadata(false));

        public static readonly DependencyProperty OptionsProperty = DependencyProperty.Register(
            nameof(Options),
            typeof(Deserted),
            typeof(EnjoyTextBox),
            new PropertyMetadata(null, OptionChangedCallback));

        private static void OptionChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is EnjoyTextBox self)
            {
                if (e.OldValue is Deserted _OldOptions)
                {
                    _OldOptions.PropertyChanged -= self.OptionsChangeEvent;
                }
                if (e.NewValue is Deserted _NewOptions)
                {
                    _NewOptions.PropertyChanged += self.OptionsChangeEvent;
                }
            }
        }

        private void OptionsChangeEvent(object? sender, PropertyChangedEventArgs e)
        {
            if (sender is not null and Deserted Options)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (Options.DoImeiFocusTextBox && Visibility == Visibility.Visible)
                    {
                        Focus();
                        //Options.DoCtClearRichBox = !Options.DoCtClearRichBox;
                    }
                });
            }
        }

        protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                if (CannelIsReadOnly)
                {
                    IsReadOnly = false;

                    InputMethod.SetIsInputMethodEnabled(this, false);

                    Task.Delay(50).ContinueWith(_ =>
                    {
                        InputMethod.SetIsInputMethodEnabled(this, true);

                        Dispatcher.Invoke(() =>
                        {
                            Focus();
                        });
                    }, TaskScheduler.FromCurrentSynchronizationContext()); //  第二个参数可无
                }
            }), DispatcherPriority.Input); //  第二个参数可无

            base.OnMouseDoubleClick(e);
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            if (!IsReadOnly && CannelIsReadOnly) IsReadOnly = true;
            base.OnLostFocus(e);
        }


    }

    /// <summary>
    /// 自定义消息框类，提供以下静态方法
    /// <para>1. Show ( InquiryDlPopupSetting )</para>
    /// <para>2. Show ( InquiryNmPopupSetting )</para>
    /// <para>3. Show ( InquiryListPopupSetting )</para>
    /// <para>4. Show ( InquiryDBPopupSetting )</para>
    /// <para>5. Show ( ShowyPrograssSetting )</para>
    /// <para>6. Show ( InquiryArgPopupSetting )</para>
    /// </summary>
    public class CustomMessageBox : Window
    {
        private static readonly ILogger Logger = Log.ForContext<CustomMessageBox>();

        private readonly ConditionalWeakTable<string, WeakReference<FrameworkElement>> SubcripElementManager = [];

        private readonly DoubleAnimation CloseAnimation = new(0, TimeSpan.FromSeconds(0.3));

        private readonly Dictionary<string, List<string>> SearchMatchMap = [];

        private readonly Dictionary<string, string> SearchResultMap = [];

        private readonly List<string> Options = ["否", "是"];

        /// <summary>
        /// <para>1. public List[string] selectedValues = [];</para>
        /// <para>2. public int index = -1;</para>
        /// <para>3. public string content = string.Empty;</para>
        /// </summary>
        public sealed class InquiryPopupInvoke
        {
            public List<string> selectedValues = [];

            public int index = -1;
        };

        /// <summary>
        /// <para>1. public string CurrentApplyDBaddress</para>
        /// <para>2. public string CurrentApplyDBkey</para>
        /// <para>3. public string CurrentApplyUnknown1;</para>
        /// <para>3. public string CurrentApplyUnknown2</para>
        /// <para>3. public int index = -1;</para>
        /// </summary>
        public sealed class PublicBlackBox
        {
            public string CurrentApplyDBaddress { set; get; } = string.Empty;

            public string CurrentApplyDBkey { set; get; } = string.Empty;

            public string CurrentApplyLogState { set; get; } = "开";

            public string CurrentApplyMMenuStyle { set; get; } = "中文";

            public int index = -1;
        };

        /// <summary>
        /// <para>Msg_Title,Msg_BodyText,Msg_Result,Msg_DelayExitTime,Msg_HAlignment,Msg_VAlignment,Msg_CloseCallback,Msg_WinRadius</para>
        /// </summary>
        public sealed class InquiryDlPopupSetting
        {
            public string Msg_Title { get; set; } = string.Empty;

            public string Msg_BodyText { get; set; } = string.Empty;

            /// <summary>
            /// 0 - fail 1 - other 2 - pass
            /// </summary>
            public int Msg_Result { get; set; } = 0;

            public double? Msg_DelayExitTime { get; set; } = null;

            public HorizontalAlignment Msg_HAlignment { get; set; } = HorizontalAlignment.Center;

            public VerticalAlignment Msg_VAlignment { get; set; } = VerticalAlignment.Center;

            public Action? Msg_CloseCallback { get; set; } = null;

            public double Msg_WinRadius { get; set; } = 5;
        }

        /// <summary>
        /// <para>Msg_Title,Msg_InquiryIcon,Msg_InquiryButtoms,Msg_BodyText,Msg_HAlignment,Msg_VAlignment,Msg_WinWidth,Msg_WinHeight,Msg_WinRadius</para>
        /// </summary>
        public sealed class InquiryNmPopupSetting
        {
            public string Msg_Title { get; set; } = string.Empty;

            public int Msg_InquiryIcon { get; set; } = 0;

            public List<string> Msg_InquiryButtoms { get; set; } = [];

            public string Msg_BodyText { get; set; } = string.Empty;

            public HorizontalAlignment Msg_HAlignment { get; set; } = HorizontalAlignment.Center;

            public VerticalAlignment Msg_VAlignment { get; set; } = VerticalAlignment.Center;

            public double? Msg_WinWidth { get; set; } = null;

            public double? Msg_WinHeight { get; set; } = null;

            public double Msg_WinRadius { get; set; } = 5;

            public bool EnableMainWindow { get; set; } = false;

            public Func<double, double, double, double, (double, double)>? Msg_Location = null;
        }

        /// <summary>
        /// <para>Msg_Title,Msg_InquiryButtoms,Msg_ItemsSource,Msg_SelectionMode,Msg_SelectionIndex,Msg_WinRadius</para>
        /// </summary>
        public sealed class InquiryListPopupSetting
        {
            public string Msg_Title { get; set; } = string.Empty;

            public ICollection<string> Msg_InquiryButtoms { get; set; } = [];

            public ICollection<string> Msg_ItemsSource { get; set; } = [];

            public SelectionMode Msg_SelectionMode { get; set; } = System.Windows.Controls.SelectionMode.Single;

            public ICollection<int> Msg_SelectionIndex { get; set; } = [];

            public double Msg_WinRadius { get; set; } = 5;
        }

        /// <summary>
        /// <para>Msg_Title,Msg_InquiryButtoms,Msg_DBSetting,Msg_WinRadius</para>
        /// </summary>
        public sealed class InquiryPBLPopupSetting
        {
            public string Msg_Title { get; set; } = string.Empty;

            public List<string> Msg_InquiryButtoms { get; set; } = [];

            public PublicBlackBox Msg_PBLSetting { get; set; } = new CustomMessageBox.PublicBlackBox();

            public double Msg_WinRadius { get; set; } = 5;
        }

        /// <summary>
        /// <para>Msg_Minnum,Msg_Maxnum,Msg_DelayExitTime,Msg_WinRadius</para>
        /// </summary>
        public sealed class ShowyPrograssSetting
        {
            public double Msg_Minnum { get; set; } = 0;

            public double Msg_Maxnum { get; set; } = 100;

            public int Msg_DelayExitTime { get; set; } = 2500;

            public double Msg_WinRadius { get; set; } = 5;
        }

        private readonly IActivityDetetorServer ActivityDetetorServer;

        private readonly IDataBaseServer DataBaseServer;

        public sealed class InquiryPopupField
        {
            public string title = string.Empty;

            public string message = string.Empty;

            public int type = 0;

            public (double, double)? size = null;

            public List<string> options = [];

            public List<string> itemsSource = [];
        };

        private static readonly InquiryPopupInvoke Push_InquiryPopupInvoke = new();

        private static readonly PublicBlackBox Push_InquiryBlackBox = new();

        public CustomMessageBox()
        {
            this.AllowsTransparency = true;         //  关键，支持透明度，可能原因为window与UIElement不一样，UIElement在xaml是直接支持设置透明度的，而WIndow则需要手动打开这个设置
            this.WindowStyle = WindowStyle.None;    //  不设置样式，由布局覆盖
            this.Background = Brushes.Transparent;  //  背景透明
            this.Opacity = 0;                       //  透明度为0

            App MyApp = (App)Application.Current;
            ActivityDetetorServer = MyApp.ServiceProvider.GetRequiredService<IActivityDetetorServer>();
            DataBaseServer = MyApp.ServiceProvider.GetRequiredService<IDataBaseServer>();

            this.Owner = Application.Current.MainWindow;
            this.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            RenderOptions.SetEdgeMode(this, EdgeMode.Unspecified); //  强制抗锯齿
            RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.Fant); //  最高质量

            this.MaxHeight = 380;
            this.MaxWidth = 410;
            this.UseLayoutRounding = true;
            this.SnapsToDevicePixels = true;
            this.ShowInTaskbar = false;
            this.Topmost = true;
            this.ResizeMode = ResizeMode.NoResize;

            this.Content = new Border
            {
                Background = "DeepWhite".FindSolidBrush(),
                BorderBrush = "Driftwood".FindSolidBrush(),
                BorderThickness = new Thickness(1),
                CornerRadius = new CornerRadius(6),
                Padding = new Thickness(4, 8, 4, 8)
            };

            CloseAnimation.Completed += DistoryPrepare;
        }

        private void DistoryPrepare(object? sender, EventArgs e)
        {
            Function.Topmast();

            WindowChrome.SetWindowChrome(this, null);
            DisposeSubcription();
            CloseAnimation.Completed -= DistoryPrepare;
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == OpacityProperty)
            {
                if (e.NewValue is double _NOpacity && _NOpacity == 0 && 
                    e.OldValue is double _OOpacity && _OOpacity > 0 && _OOpacity < 1)
                {
                    Application.Current.MainWindow.ShowActivated = true;
                    this.Close();
                }
            }
            base.OnPropertyChanged(e);
        }

        protected override void OnContentRendered(EventArgs e)
        {
            this.Dispatcher.InvokeAsync(() =>
            {   
                //  内容渲染完成后开始动画
                DoubleAnimation visibleAnimation = new(1, TimeSpan.FromSeconds(0.3));
                this.BeginAnimation(OpacityProperty, visibleAnimation);
            });
            base.OnContentRendered(e);
        }

        /// <summary>
        /// result: 0 - fail, 1 - doing, 2 - pass
        /// </summary>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <param name="result"></param>
        public static async Task<Action> Show(InquiryDlPopupSetting setting)
        {
            CustomMessageBox? messageBox = null;

            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                messageBox = new()
                {
                    Height = 190,
                    Width = 360,
                };

                Grid mainGrid = new()
                {
                    Background = Brushes.Transparent,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(42) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(42) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 30.0,
                };
                TextBlock Title = new()
                {
                    Text = setting.Msg_Title,
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };
                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                EnjoyTextBox MessageTextBox = new()
                {
                    IsReadOnly = true,
                    Text = setting.Msg_BodyText,
                    TextWrapping = TextWrapping.Wrap,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    FontSize = 29.0,
                    Margin = new Thickness(3),
                    Padding = new Thickness(5),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    Background = Brushes.Transparent,
                    HorizontalContentAlignment = setting.Msg_HAlignment,
                    VerticalContentAlignment = setting.Msg_VAlignment,
                    BorderBrush = Brushes.Transparent
                };

                if (setting.Msg_Result == 0)
                {
                    HintIcon.Text = "\ue605";
                    HintIcon.Foreground = "SunsetCoral".FindSolidBrush();
                    MessageTextBox.Foreground = "SunsetCoral".FindSolidBrush();
                }
                else if (setting.Msg_Result == 1)
                {
                    HintIcon.Text = "\ue6eb";
                    HintIcon.Foreground = "RoyalSignal".FindSolidBrush();
                    MessageTextBox.Foreground = "RoyalSignal".FindSolidBrush();
                }
                else if (setting.Msg_Result == 2)
                {
                    HintIcon.Text = "\ue603";
                    HintIcon.Foreground = "JadeFlow".FindSolidBrush();
                    MessageTextBox.Foreground = "JadeFlow".FindSolidBrush();
                }

                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 0, MessageTextBox);

                //Application.Current.MainWindow.IsEnabled = false;

                if (setting.Msg_DelayExitTime.HasValue)
                {
                    DispatcherTimer? closeTimer = null;
                    closeTimer = new DispatcherTimer(
                                    TimeSpan.FromMilliseconds(setting.Msg_DelayExitTime.Value),
                                    DispatcherPriority.Normal, //  改为 DispatcherPriority.SystemIdle
                                    (s, e) =>
                                    {
                                        closeTimer?.Stop();
                                        Application.Current.MainWindow.IsEnabled = true;
                                        messageBox.Close();
                                        setting.Msg_CloseCallback?.Invoke();
                                    },
                                    Application.Current.Dispatcher);
                }

                if (messageBox.Content is Border _Border)
                {
                    _Border.CornerRadius = new CornerRadius(setting.Msg_WinRadius);
                    _Border.Child = mainGrid;
                }

                messageBox.Show();

            });

            return () =>
            {
                Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    Application.Current.MainWindow.IsEnabled = true;
                    messageBox?.Close();
                    setting.Msg_CloseCallback?.Invoke();
                }, DispatcherPriority.Background);
            };
        }

        public static async Task<InquiryPopupInvoke> Show(InquiryNmPopupSetting setting)
        {
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                CustomMessageBox messageBox = new()
                {
                    Width = setting.Msg_WinWidth ?? 410,
                    Height = setting.Msg_WinHeight ?? 254
                };

                Logger.Print(RuntimeLog.LogType.Info, setting.Msg_WinWidth ?? 410, setting.Msg_WinHeight ?? 254);

                Grid mainGrid = new()
                {
                    Background = Brushes.Transparent,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(42) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(42) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 30.0,
                };

                TextBlock Title = new()
                {
                    Text = setting.Msg_Title,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };

                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                switch (setting.Msg_InquiryIcon)
                {
                    case 0:
                        HintIcon.Text = "\ue607";
                        HintIcon.Foreground = "JadeFlow".FindSolidBrush();
                        break;
                    case 1:
                        HintIcon.Text = "\ue604";
                        HintIcon.Foreground = "MustardPop".FindSolidBrush();
                        break;
                    case 2:
                        HintIcon.Text = "\ue662";
                        HintIcon.Foreground = "SunsetCoral".FindSolidBrush();
                        break;
                }

                EnjoyTextBox MessageTextBox = new()
                {
                    IsReadOnly = true,
                    Text = setting.Msg_BodyText,
                    TextWrapping = TextWrapping.Wrap,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    FontSize = 14.0,
                    Margin = new Thickness(3),
                    Padding = new Thickness(5),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    Background = Brushes.Transparent,
                    HorizontalContentAlignment = setting.Msg_HAlignment,
                    VerticalContentAlignment = setting.Msg_VAlignment,
                    BorderBrush = Brushes.Transparent
                };

                Grid bottonGrid = new()
                {
                    MinHeight = 30.0,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 10)
                };

                int column = 0;
                foreach (var button in setting.Msg_InquiryButtoms)
                {
                    bottonGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                    VariantButton variant = new()
                    {
                        Content = button,
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        FontSize = 13.0,
                        Foreground = "DeepMatrix".FindSolidBrush(),
                        Margin = new Thickness(5, 0, 5, 0),
                        MinWidth = 110.0,
                        MinHeight = 28,
                        HorizontalAlignment = HorizontalAlignment.Center
                    };
                    bottonGrid.SetGridWidget(0, column, variant);
                    messageBox.SubcripElementManager.Add(button, new WeakReference<FrameworkElement>(variant));
                    variant.PreviewMouseUp += messageBox.ButtonClick;
                    column++;
                }
                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 0, MessageTextBox);
                mainGrid.SetGridWidget(2, 0, bottonGrid);

                if (messageBox.Content is Border _Border)
                {
                    _Border.CornerRadius = new CornerRadius(setting.Msg_WinRadius);
                    _Border.Child = mainGrid;
                }

                (double, double)? location = setting.Msg_Location?.Invoke(
                    Application.Current.MainWindow.Left, 
                    Application.Current.MainWindow.Top,
                    Application.Current.MainWindow.Width,
                    Application.Current.MainWindow.Height);

                if (location is not null)
                {
                    messageBox.WindowStartupLocation = WindowStartupLocation.Manual;
                    messageBox.Left = location.Value.Item1;
                    messageBox.Top = location.Value.Item2;
                }

                messageBox.ShowDialog();
            });
            return CustomMessageBox.Push_InquiryPopupInvoke;
        }

        public static InquiryPopupInvoke Show(InquiryListPopupSetting setting)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                CustomMessageBox messageBox = new();

                Grid mainGrid = new()
                {
                    Background = Brushes.Transparent,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(40) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    Text = "\ue607",
                    Foreground = "JadeFlow".FindSolidBrush(),
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    FontSize = 30.0,
                };

                TextBlock Title = new()
                {
                    Text = setting.Msg_Title,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };

                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                ListBox MessageListBox = new()
                {
                    FontFamily = "YaHei".FindSource<FontFamily>(),
                    FontSize = 12.0,
                    SelectionMode = setting.Msg_SelectionMode,
                    Style = "ListBoxTemplate".FindSource<Style>(),
                    BorderThickness = new Thickness(0),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    HorizontalContentAlignment = HorizontalAlignment.Left,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    ItemsSource = setting.Msg_ItemsSource
                };
                if (setting.Msg_SelectionIndex is null)
                {
                    MessageListBox.SelectedIndex = 0;
                }
                else
                {
                    if (setting.Msg_SelectionMode == SelectionMode.Extended || setting.Msg_SelectionMode == SelectionMode.Extended)
                    {
                        foreach (var index in setting.Msg_SelectionIndex)
                        {
                            DependencyObject dependency = MessageListBox.ItemContainerGenerator.ContainerFromIndex(index);
                            if (dependency is ListBoxItem item)
                            {
                                item.IsSelected = true;
                            }
                        }
                    }
                    else
                    {
                        MessageListBox.SelectedIndex = 0;
                    }
                }

                Grid bottonGrid = new()
                {
                    MinHeight = 30.0,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 10)
                };

                int column = 0;
                foreach (var button in setting.Msg_InquiryButtoms)
                {
                    bottonGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                    VariantButton variant = new ()
                    {
                        Content = button,
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        FontSize = 11.0,
                        Foreground = "DeepMatrix".FindSolidBrush(),
                        Margin = new Thickness(5, 0, 5, 0),
                        MinWidth = 100.0,
                        MinHeight = 25
                    };
                    bottonGrid.SetGridWidget(0, column, variant);
                    messageBox.SubcripElementManager.Add(button, new WeakReference<FrameworkElement>(variant));
                    variant.PreviewMouseUp += messageBox.ButtonClick;
                    column++;

                }
                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 1, MessageListBox);
                mainGrid.SetGridWidget(2, 0, bottonGrid);

                if (messageBox.Content is Border _Border)
                {
                    _Border.CornerRadius = new CornerRadius(setting.Msg_WinRadius);
                    _Border.Child = mainGrid;
                }

                messageBox.ShowDialog();
                messageBox.DisposeSubcription();

                List<string> SelectItems = [];
                foreach (var select in MessageListBox.SelectedItems)
                {
                    if (select is not null) SelectItems.Add(select.GetSafetyChar());
                }
                CustomMessageBox.Push_InquiryPopupInvoke.selectedValues = SelectItems;
            });
            return CustomMessageBox.Push_InquiryPopupInvoke;
        }

        public static PublicBlackBox Show(InquiryPBLPopupSetting setting)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                CustomMessageBox messageBox = new()
                {
                    MaxWidth = 500,
                    MaxHeight = 370
                };

                Grid mainGrid = new()
                {
                    Background = Brushes.Transparent,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center,
                    Height = 48.0
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(40) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    Text = "\ue607",
                    Foreground = "JadeFlow".FindSolidBrush(),
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 28.0,
                };

                TextBlock Title = new()
                {
                    Text = setting.Msg_Title,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };

                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                Grid mainContentGrid = new()
                {
                    Margin = new Thickness(12),
                    Background = Brushes.Transparent,
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                };

                mainContentGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(80) });
                mainContentGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(56) });
                mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(56) });
                mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(56) });
                mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(56) });

                TextBlock DBhint = new()
                {
                    Text = "数据库切换",
                    TextAlignment = TextAlignment.Center,
                    Foreground = "PineTrail".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TextBlock Loghint = new()
                {
                    Text = "打开日志",
                    TextAlignment = TextAlignment.Center,
                    Margin = new Thickness(0, 4, 0, 4),
                    Foreground = "PineTrail".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TextBlock MmStyleHint = new()
                {
                    Text = "主菜单风格",
                    TextAlignment = TextAlignment.Center,
                    Margin = new Thickness(0, 4, 0, 4),
                    Foreground = "PineTrail".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center
                };

                EnjoyCombobox DBAddressSelect = new()
                {
                    ItemsSource = new List<string>() { "云数据库", "本地数据库" },
                    SelectedValue = setting.Msg_PBLSetting.CurrentApplyDBaddress,
                    Height = 32,
                    IsEditable = true,
                    Margin = new Thickness(0, 4, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                EnjoyCombobox DBPasswordSelect = new()
                {
                    ItemsSource = new List<string>() { "云数据库", "Auto" },
                    SelectedValue = setting.Msg_PBLSetting.CurrentApplyDBkey,
                    Height = 32,
                    IsEditable = true,
                    Margin = new Thickness(0, 4, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                EnjoyCombobox RuntimeLogSelect = new()
                {
                    ItemsSource = new List<string>() { "开", "关" },
                    SelectedValue = setting.Msg_PBLSetting.CurrentApplyLogState,
                    IsEditable = true,
                    Height = 32,
                    IsReadOnly = true,
                    Margin = new Thickness(0, 4, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                EnjoyCombobox MainmStyleSelect = new()
                {
                    ItemsSource = new List<string>() { "中文", "图标" },
                    SelectedValue = setting.Msg_PBLSetting.CurrentApplyMMenuStyle,
                    IsEditable = true,
                    Height = 32,
                    IsReadOnly = true,
                    Margin = new Thickness(0, 4, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                mainContentGrid.SetGridWidget(0, 0, 2, 0, DBhint);
                mainContentGrid.SetGridWidget(0, 1, DBAddressSelect);
                mainContentGrid.SetGridWidget(1, 1, DBPasswordSelect);
                mainContentGrid.SetGridWidget(2, 0, Loghint);
                mainContentGrid.SetGridWidget(2, 1, RuntimeLogSelect);
                mainContentGrid.SetGridWidget(3, 0, MmStyleHint);
                mainContentGrid.SetGridWidget(3, 1, MainmStyleSelect);

                int column = 0;
                Grid bottonGrid = new()
                {
                    MinHeight = 30.0,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 10)
                };
                foreach (var button in setting.Msg_InquiryButtoms)
                {
                    bottonGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                    VariantButton variant = new ()
                    {
                        Content = button,
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        FontSize = 11.0,
                        Foreground = "DeepMatrix".FindSolidBrush(),
                        Margin = new Thickness(5, 0, 5, 0),
                        MinWidth = 100.0,
                        MinHeight = 25
                    };
                    bottonGrid.SetGridWidget(0, column, variant);
                    messageBox.SubcripElementManager.Add(button, new WeakReference<FrameworkElement>(variant));
                    variant.PreviewMouseUp += messageBox.ButtonClick;
                    column++;

                }
                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 1, mainContentGrid);
                mainGrid.SetGridWidget(2, 0, bottonGrid);

                if (messageBox.Content is Border _Border)
                {
                    _Border.CornerRadius = new CornerRadius(setting.Msg_WinRadius);
                    _Border.Child = mainGrid;
                }

                messageBox.ShowDialog();
                messageBox.DisposeSubcription();

                CustomMessageBox.Push_InquiryBlackBox.CurrentApplyDBaddress = DBAddressSelect.SelectedValue.GetSafetyChar();
                CustomMessageBox.Push_InquiryBlackBox.CurrentApplyDBkey = DBPasswordSelect.SelectedValue.GetSafetyChar();
                CustomMessageBox.Push_InquiryBlackBox.CurrentApplyLogState = RuntimeLogSelect.SelectedValue.GetSafetyChar();
                CustomMessageBox.Push_InquiryBlackBox.CurrentApplyMMenuStyle = MainmStyleSelect.SelectedValue.GetSafetyChar();

            });
            return CustomMessageBox.Push_InquiryBlackBox;
        }

        public static async Task<Action<double, string?>> Show(ShowyPrograssSetting setting)
        {
            CustomMessageBox? messageBox = null;
            ProgressBar? Prograss = null;
            EnjoyTextBox? HintBox = null;

            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                messageBox = new()
                {
                    MaxHeight = 130,
                };

                Grid mainGrid = new()
                {
                    Background = Brushes.Transparent,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Center
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(33) });

                HintBox = new()
                {
                    Background = Brushes.Transparent,
                    FontFamily = "YaHei".FindSource<FontFamily>(),
                    Foreground = "DeepWhite".FindSolidBrush(),
                    TextWrapping = TextWrapping.Wrap,
                    FontSize = 16,
                    BorderThickness = new Thickness(0),
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center,
                };

                Prograss = new()
                {
                    Background = "DeepWhite".FindSolidBrush(),
                    Margin = new Thickness(0, 8, 0, 8),
                    Minimum = setting.Msg_Minnum,
                    Maximum = setting.Msg_Maxnum,
                    Value = setting.Msg_Minnum,
                };

                mainGrid.SetGridWidget(0, 0, HintBox);
                mainGrid.SetGridWidget(1, 0, Prograss);

                if (messageBox.Content is Border _Border)
                {
                    _Border.Background = "OliveGrove".FindSolidBrush();
                    _Border.Padding = new Thickness(8, 2, 8, 2);
                    _Border.CornerRadius = new CornerRadius(setting.Msg_WinRadius);
                    _Border.Child = mainGrid;
                }

                messageBox.Show();
            });
            return (_processValue, hint) =>
            {
                Application.Current.Dispatcher.BeginInvoke(async () =>
                {
                    if (Prograss is not null && messageBox is not null && HintBox is not null)
                    {
                        if (Math.Abs(Prograss.Value - _processValue) >= 2 || _processValue >= 100.0)
                        {
                            Prograss.Value = _processValue;
                        }

                        if (hint is not null) HintBox.Text = hint;

                        if (_processValue >= setting.Msg_Maxnum)
                        {
                            await Task.Delay(1000);
                            if (_processValue >= setting.Msg_Maxnum)
                            {
                                await Task.Delay(setting.Msg_DelayExitTime);
                                messageBox.Close();
                            }
                        }
                    }
                }, System.Windows.Threading.DispatcherPriority.Background);
            };
        }

        private void ButtonClick(object sender, MouseButtonEventArgs e)
        {
            if (sender is VariantButton variant)
            {
                int index = 0;
                foreach (var i in SubcripElementManager)
                {
                    if (i.Value.TryGetTarget(out FrameworkElement? _Framework) && _Framework is not null and Button _Button)
                    {
                        if (i.Key == variant.Content.GetSafetyChar())
                        {
                            Push_InquiryPopupInvoke.index = index;
                            break;
                        }
                        index++;
                    }
                }
                Push_InquiryBlackBox.index = Push_InquiryPopupInvoke.index;
            }

            GetUnautoArgcontent();
            this.BeginAnimation(OpacityProperty, CloseAnimation);
        }

        private void ToggleCheck(object sender, RoutedEventArgs e)
        {
            if (sender is EnjoyToggleButton button)
            {
                this.Dispatcher.InvokeAsync(() =>
                {
                    SearchResultMap["OrderLock"] = $"{button.IsChecked}";
                    if (button.IsChecked is not null and bool _IsChecked)
                    {
                        if (_IsChecked)
                        {
                            button.BorderBrush = "ElectricLime".FindSolidBrush();
                            button.Foreground = "SunsetCoral".FindSolidBrush();
                        }
                        else
                        {
                            button.BorderBrush = "Driftwood".FindSolidBrush();
                            button.Foreground = "DeepMatrix".FindSolidBrush();
                        }
                    }
                }, DispatcherPriority.Background);
            }
        }

        private void DisposeSubcription()
        {
            foreach (var pair in SubcripElementManager)
            {
                if (pair.Value.TryGetTarget(out FrameworkElement? _Frame))
                {
                    if (_Frame is Button _Button)
                    {
                        _Button.PreviewMouseUp -= ButtonClick;
                    }

                    else if (_Frame is EnjoyToggleButton _Toggle)
                    {
                        if (_Toggle.Name == "ORDER")
                        {
                            _Toggle.Checked -= ToggleCheck;
                            _Toggle.Unchecked -= ToggleCheck;
                        }
                    }
                }
            }

            SubcripElementManager.Clear();
        }

        private void GetUnautoArgcontent()
        {
            foreach (var _pair in SubcripElementManager) //  遍历所有文本框
            {
                if (_pair.Value.TryGetTarget(out FrameworkElement? _Framework) &&
                    _Framework is not null and TextBox _TextBox)
                {
                    if (SearchResultMap.ContainsKey(_TextBox.Name))
                    {
                        SearchResultMap[_TextBox.Name] = _TextBox.Text;
                    }
                    else
                    {
                        SearchResultMap.TryAdd(_TextBox.Name, _TextBox.Text);
                    }
                }
            }
            SubcripElementManager.Clear();
        }

    }

    public class VariantButton : Button
    {
        public VariantButton()
        {
            FontFamily = "YaHei".FindSource<FontFamily>();

            Background = "CoffeeIncrease".FindSolidBrush();

            Foreground = "DeepMatrix".FindSolidBrush();
        }

        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(nameof(CornerRadius), typeof(CornerRadius), typeof(VariantButton), new PropertyMetadata(new CornerRadius(3)));

        public static readonly DependencyProperty MouseHoverBdColorProperty =
            DependencyProperty.Register(nameof(MouseHoverBdColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("DeepMatrix".FindSolidBrush()));

        public static readonly DependencyProperty MouseHoverBgColorProperty =
            DependencyProperty.Register(nameof(MouseHoverBgColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("DeepWhite".FindSolidBrush()));

        public static readonly DependencyProperty MousePreeBdColorProperty =
            DependencyProperty.Register(nameof(MousePreeBdColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("BurgundyNight".FindSolidBrush()));

        public static readonly DependencyProperty MousePreeBgColorProperty =
            DependencyProperty.Register(nameof(MousePreeBgColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("ArcticMist".FindSolidBrush()));

        public CornerRadius CornerRadius
        {
            set { SetValue(CornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        }

        public Brush MouseHoverBgColor
        {
            get { return (Brush)GetValue(MouseHoverBgColorProperty); }
            set { SetValue(MouseHoverBgColorProperty, value); }
        }

        public Brush MousePreeBgColor
        {
            get { return (Brush)GetValue(MousePreeBgColorProperty); }
            set { SetValue(MousePreeBgColorProperty, value); }
        }

        public Brush MouseHoverBdColor
        {
            get { return (Brush)GetValue(MouseHoverBdColorProperty); }
            set { SetValue(MouseHoverBdColorProperty, value); }
        }

        public Brush MousePreeBdColor
        {
            get { return (Brush)GetValue(MousePreeBdColorProperty); }
            set { SetValue(MousePreeBdColorProperty, value); }
        }
    }

    public class EnjoyRichTextBox : RichTextBox
    {
        public enum TextType
        {
            Normal,
            HyperLink
        }

        public class Text
        {
            public TextType TxType { set; get; } = TextType.Normal;

            public string Contnet { set; get; } = string.Empty;

            public string Family { set; get; } = "Consolas";

            public FontWeight FontWeight { set; get; } = FontWeights.Normal;

            public double FontSize { set; get; } = 15;

            public string Foreground { set; get; } = "DeepMatrix";

            public string Background { set; get; } = "TransParent";

            public Thickness Margin { set; get; } = new Thickness(0, 3, 0, 3);

            public Thickness Padding { set; get; } = new Thickness(0, 1, 0, 1);

            public object? BindingData { set; get; } = null;
        }

        private Ruined? Ashbin = null;

        private ScrollViewer? ScrollView = null;

        public int CacheLength { set; get; } = 200;

        public class HighLightInfoBase
        {
            public Brush? Background = null;
            public Brush? Foreground = null;
            public FontFamily? Family = null;
            public double? FontSize = null;

            public HighLightInfoBase(string? _background = null,
                                     string? _foreground = null,
                                     FontFamily? _family = null,
                                     double? _fontsize = null)
            {
                var convert = new BrushConverter();
                if (_background != null)
                {
                    object? back = convert.ConvertFrom(_background);
                    if (back != null) Background = (Brush)back;
                }
                if (_foreground != null)
                {
                    object? fore = convert.ConvertFrom(_foreground);
                    if (fore != null) Foreground = (Brush)fore;
                }
                Family = _family;
                FontSize = _fontsize;

            }
        }

        public sealed class HighLightInfoGroup(string _content,
                                  bool _isRegexp,
                                  string? _background = null,
                                  string? _foreground = null,
                                  FontFamily? _family = null,
                                  double? _fontsize = null) : HighLightInfoBase(_background, _foreground, _family, _fontsize)
        {
            public bool isRegexp = _isRegexp;
            public string Content = _content;
        }

        public EnjoyRichTextBox()
        {
            this.IsDocumentEnabled = true;
            this.Focusable = true;
            this.FontSize = 20;
            this.AddHandler(Hyperlink.PreviewMouseDownEvent, new MouseButtonEventHandler(HyperLinkPressEvent), true);
            WeakEventManager<EnjoyRichTextBox, RoutedEventArgs>.AddHandler(this, nameof(Loaded), CompleteLoaded);
        }

        public static readonly ILogger Logger = Log.ForContext<EnjoyRichTextBox>();

        public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
            nameof(CornerRadius),
            typeof(CornerRadius),
            typeof(EnjoyRichTextBox));

        public static readonly DependencyProperty IsScrollToEndProperty = DependencyProperty.Register(
            nameof(IsScrollToEnd),
            typeof(bool),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(true));

        public static readonly DependencyProperty ScrollToEndKeyProperty = DependencyProperty.Register(
              nameof(ScrollToEndKey),
              typeof(Key),
              typeof(EnjoyRichTextBox),
              new PropertyMetadata(Key.None));

        public static readonly DependencyProperty DymanicContentCollectionProperty = DependencyProperty.Register(
            nameof(DymanicContentCollection),
            typeof(ObservableCollection<object>),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(null, DymanicContentChangeCallBack));

        public static readonly DependencyProperty HighLightCollectionProperty = DependencyProperty.Register(
            nameof(HighLightCollection),
            typeof(ObservableCollection<HighLightInfoGroup>),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(new ObservableCollection<HighLightInfoGroup>()));

        public static readonly DependencyProperty DocuContentPushProperty = DependencyProperty.Register(
            nameof(CmdDocuContentPush),
            typeof(ICommand),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(null));

        public static readonly DependencyProperty HyperlinkClickProperty = DependencyProperty.Register(
            nameof(CmdHyperlinkClick),
            typeof(ICommand),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(null));

        public static readonly DependencyProperty OptionsProperty = DependencyProperty.Register(
            nameof(Options),
            typeof(Deserted),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(null, OptionChangedCallback));

        private static void OptionChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is EnjoyRichTextBox self)
            {
                if (e.OldValue is Deserted _OldOptions)
                {
                    _OldOptions.PropertyChanged -= self.OptionsChangeEvent;
                }
                
                if (e.NewValue is Deserted _NewOptions)
                {
                    _NewOptions.PropertyChanged += self.OptionsChangeEvent;
                }
            }
        }

        private void OptionsChangeEvent(object? sender, PropertyChangedEventArgs e)
        {
            if (sender is not null and Deserted Options)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (Options.DoCtClearRichBox && Visibility == Visibility.Visible)
                    {
                        Document.Blocks.Clear();
                        Options.DoCtClearRichBox = !Options.DoCtClearRichBox;
                    }
                    
                    if (Options.CapCTRichBox && Visibility == Visibility.Visible)
                    {
                        TextPointer start = Document.ContentStart;
                        TextPointer end = Document.ContentEnd;
                        TextRange getRange = new(start, end);
                        string DocuContent = getRange.Text;
                        CmdDocuContentPush?.Execute(DocuContent);
                        Options.CapCTRichBox = !Options.CapCTRichBox;
                    }
                });
            }
        }

        public Deserted Options
        {
            set
            {
                SetValue(OptionsProperty, value);
            }
            get
            {
                return (Deserted)GetValue(OptionsProperty);
            }
        }

        public ICommand CmdDocuContentPush
        {
            get => (ICommand)GetValue(DocuContentPushProperty);
            set => SetValue(DocuContentPushProperty, value);
        }

        public ICommand CmdHyperlinkClick
        {
            get => (ICommand)GetValue(HyperlinkClickProperty);
            set => SetValue(HyperlinkClickProperty, value);
        }

        public CornerRadius CornerRadius
        {
            set
            {
                SetValue(CornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(CornerRadiusProperty);
            }
        }

        public bool IsScrollToEnd
        {
            set
            {
                SetValue(IsScrollToEndProperty, value);
            }
            get
            {
                return (bool)GetValue(IsScrollToEndProperty);
            }
        }

        public Key ScrollToEndKey
        {
            set
            {
                SetValue(ScrollToEndKeyProperty, value);
            }
            get
            {
                return (Key)GetValue(ScrollToEndKeyProperty);
            }
        }

        public ObservableCollection<object> DymanicContentCollection
        {
            set
            {
                SetValue(DymanicContentCollectionProperty, value);
            }
            get
            {
                return (ObservableCollection<object>)GetValue(DymanicContentCollectionProperty);
            }
        }

        public ObservableCollection<HighLightInfoGroup> HighLightCollection
        {
            set
            {
                SetValue(HighLightCollectionProperty, value);
            }
            get
            {
                return (ObservableCollection<HighLightInfoGroup>)GetValue(HighLightCollectionProperty);
            }
        }

        public async void CompleteLoaded(object? sender, RoutedEventArgs e)
        {
            Ashbin = new Ruined(this, () => {
                this.RemoveHandler(Hyperlink.PreviewMouseDownEvent, new MouseButtonEventHandler(HyperLinkPressEvent));
                Ashbin = null; 
            });

           if (await this.GetVisual<RichTextBox, ScrollViewer>(new Server.Visual.VisualArg
            {
                Orient = Server.Visual.VisualOrient.Bottom,
                GetFirst = true
            }) is not null and ScrollViewer _ScrollViewer)
            {
                ScrollView = _ScrollViewer;
            }

            WeakEventManager<EnjoyRichTextBox, RoutedEventArgs>.RemoveHandler(this, nameof(Loaded), CompleteLoaded);
        }

        public static void DymanicContentChangeCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is not null and EnjoyRichTextBox self)
            {
                if (e.OldValue is ObservableCollection<object> oldCollection)
                {
                    WeakEventManager<INotifyCollectionChanged, NotifyCollectionChangedEventArgs>
                        .RemoveHandler(oldCollection, nameof(ObservableCollection<object>.CollectionChanged), self.CollectionContentChange);
                }


                if (e.NewValue is ObservableCollection<object> newCollection)
                {
                    WeakEventManager<INotifyCollectionChanged, NotifyCollectionChangedEventArgs>
                        .AddHandler(newCollection, nameof(ObservableCollection<object>.CollectionChanged), self.CollectionContentChange);
                }
            }
        }

        public void CollectionContentChange(object? sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems is not null)
            {
                foreach (var text in e.NewItems)
                {
                    if (text is Text _Text)
                    {
                        AppendParaGragh(_Text);
                    }
                    else if (text is string _string)
                    {
                        AppendParaGragh
                        (
                            new Text
                            {
                                Contnet = _string,
                                TxType = TextType.Normal
                            }
                        );
                    }
                }

                Dispatcher.Invoke(() =>
                {
                    if (sender is ObservableCollection<object> Collection && Collection.Count > CacheLength)
                    {
                        Logger.Print(RuntimeLog.LogType.Debug, $"trigger richtextbox auto clear start when lenght {Collection.Count}");

                        var NewItems = Collection.Skip(CacheLength);

                        Collection.Reteller(NewItems);

                        Logger.Print(RuntimeLog.LogType.Debug, $"trigger richtextbox auto clear complete when lenght {Collection.Count}");
                    }
                });
            }
        }

        public static Paragraph MatchForHighLight(Text _Text)
        {
            Paragraph paragraph = new()
            {
                Margin = _Text.Margin,
                Padding = _Text.Padding,
                LineHeight = _Text.FontSize,
                LineStackingStrategy = LineStackingStrategy.BlockLineHeight
            };
            paragraph.Inlines.Add(GetInline(_Text));
            return paragraph;
        }

        private static Inline GetInline(Text _Text)
        {
            Run _Run = new (_Text.Contnet)
            {
                FontFamily = _Text.Family.FindSource<FontFamily>(),
                FontSize = _Text.FontSize,
                Foreground = _Text.Foreground.FindSolidBrush(),
                Background = _Text.Background.FindSolidBrush(),
                FontWeight = _Text.FontWeight
            };

            if (_Text.TxType == TextType.Normal)
            {
                return _Run;
            }
            
            else if (_Text.TxType == TextType.HyperLink)
            {
                Hyperlink _Link = new(_Run)
                {
                    IsEnabled = true,
                    Tag = _Text.BindingData,
                };

                return _Link;
            }
            
            else
            {
                return _Run;
            }
        }

        protected override async void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            DependencyObject? Source = e.OriginalSource as DependencyObject;

            if (Source is not null && await Source.GetLogical<Span>(new Server.Visual.VisualArg { GetFirst = true }) is not null and Hyperlink)
            {
                Mouse.OverrideCursor = Cursors.Hand;
            }
            else
            {
                Mouse.OverrideCursor = null;
            }
        }

        private async void HyperLinkPressEvent(object sender, MouseButtonEventArgs e)
        {
            DependencyObject? Source = e.OriginalSource as DependencyObject;
            if (Source is not null && await Source.GetLogical<Span>(new Server.Visual.VisualArg { GetFirst = true }) is not null and Hyperlink _Hyperlink)
            {
                //需要二次操作的参数
                if (_Hyperlink.Tag is HyperlinkBack _HyperlinkBack && 
                    _HyperlinkBack.BindingData is EnjoyContentPopue.InfoPakage _InfoPakage)
                {
                    Window Win = Application.Current.MainWindow;
                    _InfoPakage.Location_X = Win.Left + e.GetPosition(Win).X;
                    _InfoPakage.Location_Y = Win.Top + e.GetPosition(Win).Y;
                    CmdHyperlinkClick.Execute(_HyperlinkBack);
                }
                else
                {
                    CmdHyperlinkClick.Execute(_Hyperlink.Tag);
                }
            }
        }

        private void AppendParaGragh(Text _Text)
        {
            Dispatcher.Invoke(() =>
            {
                if (this.Document != null)
                {
                    Document.Blocks.Add(MatchForHighLight(_Text));
                    if (IsScrollToEnd) ScrollToEnd();
                }
            });
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            if (ScrollToEndKey == Key.None)
            {
                IsScrollToEnd = true;
            }
            else
            {
                if (e.Key == ScrollToEndKey)
                {
                    IsScrollToEnd = true;
                }
            }
            base.OnKeyUp(e);
        }

        protected async override void OnMouseWheel(MouseWheelEventArgs e)
        {
            Enum.GetValues(typeof(Key));
            if (e.Delta > 0)
            {
                await Task.Yield();
                IsScrollToEnd = false;
            }

            if (ScrollView is not null &&
                ScrollView.ScrollableHeight - ScrollView.VerticalOffset <= Math.Round(ScrollView.ViewportHeight / 3, 1))
            {
                IsScrollToEnd = true;
            }
            base.OnMouseWheel(e);
        }
    }

    public class EnjoyListBox : ListBox
    {
        private MouseButtonEventHandler? MousePressHandle = null;

        private WeakReference<Border>? LastBorder = null;

        public EnjoyListBox()
        {
            this.PreviewMouseDown += ItemClick;
            this.SelectionChanged += SelectedChange;
        }

        public ICommand CmdSelectItems
        {
            get => (ICommand)GetValue(SelectItemsProperty);
            set => SetValue(SelectItemsProperty, value);
        }

        public ICommand CmdItemEditInfo
        {
            get => (ICommand)GetValue(ItemEditInfoCommandProperty);
            set => SetValue(ItemEditInfoCommandProperty, value);
        }

        public readonly ILogger Logger = Log.ForContext<EnjoyListBox>();

        public async void SelectedChange(object d, SelectionChangedEventArgs e)
        {
            DependencyObject DependencyObject = (DependencyObject)e.OriginalSource;

            DependencyObject DependencyItem = ItemContainerGenerator.ContainerFromItem(SelectedItem);

            if (DependencyItem is not null and ListBoxItem _ListBoxItem)
            {
                object? Gvisual = await _ListBoxItem.GetVisual<Grid, Border>(new Server.Visual.VisualArg
                {
                    Orient = Server.Visual.VisualOrient.Bottom,
                    SourceNames = ["edit"]
                });

                CmdSelectItems.Execute(SelectedItems.Cast<CommandStruct>().ToList());
                if (Gvisual is not null and Border _Border)
                {
                    await this.Dispatcher.InvokeAsync(() =>
                    {
                        if (DependencyItem is not null && _ListBoxItem.Content is CommandStruct commandData)
                        {
                            int index = ItemContainerGenerator.IndexFromContainer(DependencyItem);

                            if (LastBorder is not null && LastBorder.TryGetTarget(out Border? _OutBorder))
                            {
                                _OutBorder.Visibility = Visibility.Collapsed;
                                _OutBorder.PreviewMouseUp -= MousePressHandle;
                                MousePressHandle = null;
                                LastBorder = null;
                            }

                            if (MousePressHandle is null)
                            {

                                LastBorder = new WeakReference<Border>(_Border);
                                MousePressHandle = (d, e) =>
                                {
                                    EditItemInfoSend(commandData, index);
                                };
                                _Border.Visibility = Visibility.Visible;
                                _Border.PreviewMouseUp += MousePressHandle;
                            }
                        }
                    });
                }
            }
        }

        private static readonly DependencyProperty SelectItemsProperty = DependencyProperty.Register(
            nameof(CmdSelectItems),
            typeof(ICommand),
            typeof(EnjoyListBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty ItemEditInfoCommandProperty = DependencyProperty.Register(
            nameof(CmdItemEditInfo),
            typeof(ICommand),
            typeof(EnjoyListBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty ItemCornerRadiusProperty = DependencyProperty.Register(
            nameof(ItemCornerRadius),
            typeof(CornerRadius),
            typeof(EnjoyListBox));

        private static readonly DependencyProperty ItemheightProperty = DependencyProperty.Register(
            nameof(Itemheight),
            typeof(double),
            typeof(EnjoyListBox),
            new PropertyMetadata(30.0));

        private static readonly DependencyProperty ScrollToViewProperty = DependencyProperty.Register(
            nameof(ScrollToView),
            typeof(CommandStruct),
            typeof(EnjoyListBox),
            new PropertyMetadata(null, ScrollToViewChange));

        public CornerRadius ItemCornerRadius
        {
            set
            {
                SetValue(ItemCornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(ItemCornerRadiusProperty);
            }
        }

        public double Itemheight
        {
            set
            {
                SetValue(ItemheightProperty, value);
            }
            get
            {
                return (double)GetValue(ItemheightProperty);
            }
        }

        public double ItemFontSize
        {
            set
            {
                SetValue(FontSizeProperty, value);
            }
            get
            {
                return (double)GetValue(FontSizeProperty);
            }
        }

        public CommandSectionModel.CommandStruct ScrollToView
        {
            set
            {
                SetValue(ScrollToViewProperty, value);
            }
            get
            {
                return (CommandSectionModel.CommandStruct)GetValue(ScrollToViewProperty);
            }
        }

        public static async void ItemClick(object sender, MouseButtonEventArgs e)
        {
            DependencyObject MouseUpDependencyObject = (DependencyObject)e.OriginalSource;
            if (await MouseUpDependencyObject.GetVisual<ListBoxItem>(new Server.Visual.VisualArg
            {
                GetFirst = true,
                Orient = Server.Visual.VisualOrient.Top
            }) is not null and ListBoxItem _ListBoxItem)
            {
                if (_ListBoxItem.IsSelected)
                {
                    _ListBoxItem.IsSelected = false;
                }
                else
                {
                    _ListBoxItem.IsSelected = true;
                }
            }
        }

        public void EditItemInfoSend(CommandStruct command, int index)
        {
            CmdItemEditInfo.Execute(new AlterCommandStruct(command, index));
        }

        public static void ScrollToViewChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            EnjoyListBox self = (EnjoyListBox)d;
            if (e.NewValue is CommandSectionModel.CommandStruct _obj)
            {
                self.Dispatcher.BeginInvoke(new Action(() =>
                {
                    self.ScrollIntoView(_obj);
                    self.SelectedItem = _obj;
                    int indexof = self.Items.IndexOf(_obj);
                    if (indexof != -1)
                    {
                        self.CmdItemEditInfo.Execute(new AlterCommandStruct(_obj, indexof));
                    }
                }));
            }
            else
            {
                self.Logger.Debug($"{e.NewValue} analysis fail");
            }
        }

    }

    public class ActivityListBox : ListBox
    {
        private readonly ILogger Logger = Log.ForContext<ActivityListBox>();

        private static readonly DependencyProperty ItemCornerRadiusProperty = DependencyProperty.Register(
            nameof(ItemCornerRadius),
            typeof(CornerRadius),
            typeof(ActivityListBox)
            );

        private static readonly DependencyProperty ItemheightProperty = DependencyProperty.Register(
            nameof(Itemheight),
            typeof(double),
            typeof(ActivityListBox)
            );

        private static readonly DependencyProperty ItemFontSizeProperty = DependencyProperty.Register(
            nameof(ItemFontSize),
            typeof(double),
            typeof(ActivityListBox)
            );

        private static readonly DependencyProperty ScrollToViewProperty = DependencyProperty.Register(
            nameof(ScrollToView),
            typeof(TestItemSurfaceSealed),
            typeof(ActivityListBox),
            new PropertyMetadata(null, ScrollToViewChange)
            );

        public CornerRadius ItemCornerRadius
        {
            set
            {
                SetValue(ItemCornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(ItemCornerRadiusProperty);
            }
        }

        public double Itemheight
        {
            set
            {
                SetValue(ItemheightProperty, value);
            }
            get
            {
                return (double)GetValue(ItemheightProperty);
            }
        }

        public double ItemFontSize
        {
            set
            {
                SetValue(FontSizeProperty, value);
            }
            get
            {
                return (double)GetValue(FontSizeProperty);
            }
        }

        public TestItemSurfaceSealed ScrollToView
        {
            set
            {
                SetValue(ScrollToViewProperty, value);
            }
            get
            {
                return (TestItemSurfaceSealed)GetValue(ScrollToViewProperty);
            }
        }

        public static void ScrollToViewChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ActivityListBox self = (ActivityListBox)d;
            if (e.NewValue is TestItemSurfaceSealed _obj)
            {
                self.Dispatcher.BeginInvoke(new Action(() =>
                {
                    self.ScrollIntoView(_obj);
                    self.SelectedItem = _obj;
                }));
            }
            else
            {
                self.Logger.Debug($"{e.NewValue} analysis fail");
            }
        }

    }

    public class EnjoySelector : ToggleButton
    {
        private static readonly ILogger Logger = Log.ForContext<EnjoySelector>();
        private static readonly ConditionalWeakTable<Control, ConnectFlag> SubscriptionKeyvaluePair = [];
        private List<string> SelectedValueJoin = [];
        private string ApplyParentKey = string.Empty;
        public EnjoySelector()
        {
            FontFamily = "YaHei".FindSource<FontFamily>() ?? new FontFamily("KaiTi");
            UseLayoutRounding = true;
            WeakEventManager<ToggleButton, MouseButtonEventArgs>.AddHandler(this, nameof(ToggleButton.PreviewMouseUp), PreViewMouseUpEvent);
        }

        public override void OnApplyTemplate()
        {
            Window window = Window.GetWindow(this);
            window.Deactivated += WindowDeactiveEventTrigger;
            window.Closed += WindowClosedEventTrigger;
        }

        public CornerRadius CornerRadius
        {
            set { SetValue(CornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        }

        public Brush NormalBdColor
        {
            set { SetValue(NormalBdColorProperty, value); }
            get { return (Brush)GetValue(NormalBdColorProperty); }
        }

        public Brush NormalBgColor
        {
            set { SetValue(NormalBgColorProperty, value); }
            get { return (Brush)GetValue(NormalBgColorProperty); }
        }

        public Brush MouseHoverBgColor
        {
            get { return (Brush)GetValue(MouseHoverBgColorProperty); }
            set { SetValue(MouseHoverBgColorProperty, value); }
        }

        public Brush MousePreeBgColor
        {
            get { return (Brush)GetValue(MousePreeBgColorProperty); }
            set { SetValue(MousePreeBgColorProperty, value); }
        }

        public Brush MouseHoverBdColor
        {
            get { return (Brush)GetValue(MouseHoverBdColorProperty); }
            set { SetValue(MouseHoverBdColorProperty, value); }
        }

        public Brush MousePreeBdColor
        {
            get { return (Brush)GetValue(MousePreeBdColorProperty); }
            set { SetValue(MousePreeBdColorProperty, value); }
        }

        public IEnumerable SelectedValue
        {
            set
            {
                SetValue(SelectedValueProperty, value);
            }
            get
            {
                return (ObservableCollection<string>)GetValue(SelectedValueProperty);
            }
        }

        public CornerRadius SleCornerRadius
        {
            set
            {
                SetValue(SleCornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(SleCornerRadiusProperty);
            }
        }

        public bool ContentChangeSwitch
        {
            set
            {
                SetValue(ContentChangeSwitchProperty, value);
            }
            get
            {
                return (bool)GetValue(ContentChangeSwitchProperty);
            }
        }

        public double Sleheight
        {
            set
            {
                SetValue(SleheightProperty, value);
            }
            get
            {
                return (double)GetValue(SleheightProperty);
            }
        }

        public double SleFontSize
        {
            set
            {
                SetValue(SleFontSizeProperty, value);
            }
            get
            {
                return (double)GetValue(SleFontSizeProperty);
            }
        }

        public double SleIconFontSize
        {
            set
            {
                SetValue(SleIconFontSizeProperty, value);
            }
            get
            {
                return (double)GetValue(SleIconFontSizeProperty);
            }
        }

        public IEnumerable ItemsSource
        {
            set
            {
                SetValue(ItemsSourceProperty, value);
            }
            get
            {
                return (IEnumerable)GetValue(ItemsSourceProperty);
            }
        }

        public IEnumerable ApplyItemsSource
        {
            set
            {
                SetValue(ApplyItemsSourceProperty, value);
            }
            get
            {
                return (IEnumerable)GetValue(ApplyItemsSourceProperty);
            }
        }

        public Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> ItemsSourcePair
        {
            set
            {
                SetValue(ItemsSourcePairProperty, value);
            }
            get
            {
                return (Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>>)GetValue(ItemsSourcePairProperty);
            }
        }

        public Brush ForegroundColor
        {
            get { return (Brush)GetValue(ForegroundColorProperty); }
            set { SetValue(ForegroundColorProperty, value); }
        }

        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(
                nameof(CornerRadius),
                typeof(CornerRadius),
                typeof(EnjoySelector),
                new PropertyMetadata(new CornerRadius(3)));

        public static readonly DependencyProperty MouseHoverBdColorProperty =
            DependencyProperty.Register(
                nameof(MouseHoverBdColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("DeepMatrix".FindSolidBrush()));

        public static readonly DependencyProperty MouseHoverBgColorProperty =
            DependencyProperty.Register(
                nameof(MouseHoverBgColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("DeepWhite".FindSolidBrush()));

        public static readonly DependencyProperty MousePreeBdColorProperty =
            DependencyProperty.Register(
                nameof(MousePreeBdColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("BurgundyNight".FindSolidBrush()));

        public static readonly DependencyProperty MousePreeBgColorProperty =
            DependencyProperty.Register(
                nameof(MousePreeBgColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("IvoryGlow".FindSolidBrush()));

        public static readonly DependencyProperty NormalBdColorProperty =
            DependencyProperty.Register(
                nameof(NormalBdColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("StormyHarbor".FindSolidBrush()));

        public static readonly DependencyProperty NormalBgColorProperty =
            DependencyProperty.Register(
                nameof(NormalBgColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("DeepWhite".FindSolidBrush()));

        public static readonly DependencyProperty ForegroundColorProperty =
            DependencyProperty.Register(
                nameof(ForegroundColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("OverBlack".FindSolidBrush()));

        private static readonly DependencyProperty SleCornerRadiusProperty =
            DependencyProperty.Register(
                nameof(SleCornerRadius),
                typeof(CornerRadius),
                typeof(EnjoySelector),
                new PropertyMetadata(new CornerRadius(8)));

        private static readonly DependencyProperty SleheightProperty =
            DependencyProperty.Register(
                nameof(Sleheight),
                typeof(double),
                typeof(EnjoySelector),
                new PropertyMetadata(28.0));

        private static readonly DependencyProperty ContentChangeSwitchProperty =
            DependencyProperty.Register(
                nameof(ContentChangeSwitch),
                typeof(bool),
                typeof(EnjoySelector),
                new PropertyMetadata(true));

        private static readonly DependencyProperty SleFontSizeProperty =
            DependencyProperty.Register(
                nameof(SleFontSize),
                typeof(double),
                typeof(EnjoySelector),
                new PropertyMetadata(15.0));

        private static readonly DependencyProperty SleIconFontSizeProperty =
            DependencyProperty.Register(
                nameof(SleIconFontSize),
                typeof(double),
                typeof(EnjoySelector),
                new PropertyMetadata(18.0));

        private static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register(
                nameof(ItemsSource),
                typeof(IEnumerable),
                typeof(EnjoySelector),
                new PropertyMetadata(null, ItemsSourceChangeEvent));

        private static readonly DependencyProperty ItemsSourcePairProperty =
            DependencyProperty.Register(
                nameof(ItemsSourcePair),
                typeof(Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>>),
                typeof(EnjoySelector),
                new PropertyMetadata(new Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>>(), ItemsSourcePairChangeEvent));

        private static readonly DependencyProperty ApplyItemsSourceProperty =
            DependencyProperty.Register(
                nameof(ApplyItemsSource),
                typeof(IEnumerable),
                typeof(EnjoySelector),
                new PropertyMetadata(null));

        private static readonly DependencyProperty SelectedValueProperty =
            DependencyProperty.Register(
                nameof(SelectedValue),
                typeof(IEnumerable),
                typeof(EnjoySelector),
                new PropertyMetadata(null, SelectedValueChangeEvent));

        private static readonly DependencyProperty SelectionPushCommandProperty =
            DependencyProperty.Register(
                nameof(SelectionPushCommand),
                typeof(ICommand),
                typeof(EnjoySelector),
                new PropertyMetadata(null));

        public ICommand? SelectionChangeStdin;

        public ICommand SelectionPushCommand
        {
            get => (ICommand)GetValue(SelectionPushCommandProperty);
            set => SetValue(SelectionPushCommandProperty, value);
        }

        public ICommand SelectionChangeCommand
        {
            set
            {
                SelectionChangeStdin = value;
            }
            get
            {
                SelectionChangeStdin ??= new EasyCommand(SelectionChangeEvent, bool () => true);
                return SelectionChangeStdin;
            }
        }

        //  如果按钮不在选择状态，恢复默认的选项
        public static void PreViewMouseUpEvent(object? sender, MouseButtonEventArgs e)
        {
            if (sender is not null and EnjoySelector self)
            {
                if (self.IsChecked is not null and bool _IsChecked && !_IsChecked)
                {
                    self.ApplyItemsSource = self.ItemsSource;
                    self.SelectedValueJoin = [];
                    self.ApplyParentKey = string.Empty;
                }
            }
        }

        public void SelectionChangeEvent(object? param)
        {
            if (param is not null)
            {
                int SelectedIndex = int.Parse(param.GetSafetyChar());
                if (ApplyItemsSource is ObservableCollection<KeyValuePairSealed> StepSelects)
                {
                    if (SelectedIndex >= 0 && SelectedIndex < StepSelects.Count)
                    {
                        KeyValuePairSealed HitIkey = StepSelects[SelectedIndex];
                        SelectedValueJoin.Add(HitIkey.Name); //  ready to combination selectedsObject reference not set to an instance of an object.

                        //  ItemsSourcePair 数据依赖于 ProductFixedOpptions ，而 ProductFixedOpptions 字典不存在子项时需要有空项，因此增加集合大小校验
                        if (SourcePairContainFromSecondaryPair(HitIkey, ItemsSourcePair, out var HitInvalues) && HitInvalues?.Count > 0 &&
                            HitInvalues is not null)
                        {
                            ApplyParentKey = HitIkey.Name;
                            ApplyItemsSource = HitInvalues;
                        }
                        else
                        {
                            SetValue(SelectedValueProperty, SelectedValueJoin);

                            SelectionPushCommand?.Execute(SelectedValueJoin.ToList());

                            if (ContentChangeSwitch &&
                                !ActivityAssistBehivor.Behivor.ProductFixedOpptions.Any(x => SelectedValueJoin.Join("").Contains(x.Key.Name)))
                            {
                                Content = SelectedValueJoin.Join(" · ");
                            }
                            ApplyItemsSource = ItemsSource;
                            SelectedValueJoin.Clear();
                            IsChecked = false;
                        }
                    }
                }
            }
        }

        public void WindowDeactiveEventTrigger(object? sender, EventArgs e)
        {
            IsChecked = false;
        }

        public void WindowClosedEventTrigger(object? sender, EventArgs e)
        {
            if (sender is not null and Window window)
            {
                window.Deactivated -= WindowDeactiveEventTrigger;
                window.Closed -= WindowClosedEventTrigger;
                WeakEventManager<ToggleButton, MouseButtonEventArgs>.RemoveHandler(this, nameof(ToggleButton.PreviewMouseUp), PreViewMouseUpEvent);
            }
            IsChecked = false;
        }

        public static void ItemsSourceChangeEvent(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is not null and EnjoySelector self && 
                e.NewValue is IEnumerable datas)
            {
                self.ApplyItemsSource = datas;
            }
        }

        public static void ItemsSourcePairChangeEvent(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is not null and EnjoySelector self && 
                e.NewValue is IDictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> datas)
            {
                self.Dispatcher.Invoke(() =>
                {
                    foreach (var i in datas)
                    {
                        if (i.Key.Name == self.ApplyParentKey)
                        {
                            self.ApplyItemsSource = i.Value;
                        }
                    }
                });
            }
        }

        private static bool SourcePairContainFromSecondaryPair(KeyValuePairSealed option,
                                                        Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> targets,
                                                        out ObservableCollection<KeyValuePairSealed>? ValidStepStruct)
        {
            foreach (var pair in targets)
            {
                if (pair.Key.Name == option.Name)
                {
                    ValidStepStruct = pair.Value;
                    return true;
                }
            }
            ValidStepStruct = null;
            return false;
        }

        private static void SelectedValueChangeEvent(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ICollection<string> Echos = [];

            if (sender is not null and EnjoySelector self &&
                e.NewValue is IEnumerable Values &&
                self.ContentChangeSwitch &&
                !ActivityAssistBehivor.Behivor.ProductFixedOpptions.Any(x => self.SelectedValueJoin.Join("").Contains(x.Key.Name)))
            {
                foreach (var i in Values) Echos.Add(i.GetSafetyChar());

                if (Echos.Count == 1)
                {
                    self.Content = Echos.First();
                }
                
                else if (Echos.Count > 1)
                {
                    self.Content = Echos.Join(" · ");
                }
            }
        }
    }

    public class MultilConfigLiBox : ListBox
    {
        private readonly ILogger Logger = Log.ForContext<MultilConfigLiBox>();
        private readonly string AttributeKey = "combobox_Attribute_key";
        private readonly string MapTValueKey = "combobox_value_key";
        private readonly string MainGridKey = "grid_primary_content_key";
        private readonly List<string> ValidAtrributes = [];
        private Ruined? Ashbin = null;

        private readonly ConditionalWeakTable<UIElement, ConnectFlag> SubscriptionKeyvaluePair = [];

        public ICommand CmdDeepSeatedCommand
        {
            set
            {
                SetValue(DeepSeatedCommandProperty, value);
            }
            get
            {
                return (ICommand)GetValue(DeepSeatedCommandProperty);
            }
        }

        public Deserted Options
        {
            set
            {
                SetValue(OptionsProperty, value);
            }
            get
            {
                return (Deserted)GetValue(OptionsProperty);
            }
        }

        private static readonly DependencyProperty DeepSeatedCommandProperty = DependencyProperty.Register(
            nameof(CmdDeepSeatedCommand),
            typeof(ICommand),
            typeof(MultilConfigLiBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty OptionsProperty = DependencyProperty.Register(
             nameof(Options),
             typeof(Deserted),
             typeof(MultilConfigLiBox),
             new PropertyMetadata(null, OptionChangedCallback));

        private static void OptionChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is MultilConfigLiBox self)
            {
                if (e.OldValue is Deserted _OldOptions)
                {
                    _OldOptions.PropertyChanged -= self.OptionsChangeEvent;
                }
                if (e.NewValue is Deserted _NewOptions)
                {
                    _NewOptions.PropertyChanged += self.OptionsChangeEvent;
                }
            }
        }

        private void OptionsChangeEvent(object? sender, PropertyChangedEventArgs e)
        {
            if (sender is not null and Deserted Options)
            {
                Dispatcher.InvokeAsync(() =>
                {
                    if (Options.CapCTAttributeConfig)
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Captrue();
                            Options.CapCTAttributeConfig = !Options.CapCTAttributeConfig;
                        });
                    }
                    if (Options.IFLoadAttrStepAddPush is not null and string _AddStep)
                    {
                        AppendStep(_AddStep);
                        Options.IFLoadAttrStepAddPush = null;
                    }
                    if (Options.IFLoadAttrItemsAddPush is not null and List<TestItemDeepSeatedSealed> AtrributeItems)
                    {

                        Items.Clear();

                        UILayoutLoder(AtrributeItems);

                        Options.IFLoadAttrItemsAddPush = null;
                    }
                });
            }
        }

        //  获取属性数据组
        private void Captrue()
        {
            List<TestItemDeepSeatedSealed> AtrributesCombination = [];

            Dispatcher.Invoke(async () =>
            {
                //  遍历所有项
                foreach (ListBoxItem item in Items)
                {
                    //  获取主布局
                    if (item.Content is Grid mainGrid && await mainGrid.GetVisual<Grid, Grid>(new Server.Visual.VisualArg
                    {
                        SourceNames = [MainGridKey],
                        GetFirst = true
                    }) is not null and Grid contentGrid)
                    {
                       
                        TestItemDeepSeatedSealed attribute = new(string.Empty); //  空属性
                        int rowCount = contentGrid.RowDefinitions.Count;
                        for (int row = 0; row < rowCount; row++)
                        {
                            var data = contentGrid.GetGridRowPairWidget<ComboBox, ComboBox>(row, AttributeKey, MapTValueKey);
                            if (data is not null)
                            {
                                string RealKey = data.Value.Key.Text;
                                string RealValue = data.Value.Value.Text;
                                ICollection<string> TranslationKeys = ActivityAssistBehivor.Behivor.AttributeTranslationMap.GetSafetyKey(RealKey);
                                if (TranslationKeys.Count == 1 &&
                                    attribute.GetField(TranslationKeys.ElementAt(0)) is not null and FieldInfo expectField &&
                                    expectField.CanSafetyConvert(RealValue, out object? value))
                                {
                                    expectField.SetValue(attribute, value);
                                }
                                else
                                {
                                    Logger.Print(RuntimeLog.LogType.Debug, "content mybe empty or convert fail");
                                }
                            }
                        }
                        AtrributesCombination.Add(attribute);
                        
                    }
                }
                CmdDeepSeatedCommand.Execute(AtrributesCombination);
            });
        }

        private void AppendStep(string stepName)
        {
            if (stepName is not null and string configName)
            {
                if (ActivityAssistBehivor.Behivor.FixedAtrributeTemplates.TryGetValue(configName, out TestItemDeepSeatedSealed? _attribute))
                {
                    List<TestItemDeepSeatedSealed> _attributes = [_attribute];
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        UILayoutLoder(_attributes);

                        this.ScrollIntoView(this.Items[^1]);
                    });
                }
            }
        }

        private void UILayoutLoder(List<TestItemDeepSeatedSealed> datas)
        {
            foreach (TestItemDeepSeatedSealed attribute in datas)
            {
                Grid ItemGrid = new()
                {
                    Name = MainGridKey,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) });
                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(6, GridUnitType.Star) });
                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

                Grid ItemOutGrid = new()
                {
                    UseLayoutRounding = true,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                };

                ItemOutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                ItemOutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(43) });
                ListBoxItem listBoxItem = new()
                {
                    Margin = new Thickness(5),
                    BorderThickness = new Thickness(4),
                    HorizontalContentAlignment = HorizontalAlignment.Stretch,
                    VerticalContentAlignment = VerticalAlignment.Stretch
                };

                if ("DynamicListBoxItemControl".FindSource<ControlTemplate>() is not null and ControlTemplate template) listBoxItem.Template = template;

                listBoxItem.BorderBrush = "RoyalSignal".FindSolidBrush();

                foreach (var field in attribute.GetFields(1))
                {
                    if (!ActivityAssistBehivor.Behivor.fieldHideds.Contains(field.Name))
                    {
                        TreeFull(ref ItemGrid, field.GetValue(attribute), field);
                    }
                }

                Grid bottonGrid = new()
                {
                    Margin = new Thickness(0, 8, 0, 8),
                };

                bottonGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(2, GridUnitType.Star) });
                bottonGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) });
                bottonGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) });

                int itemIndex = 1;
                itemIndex += Items.Count;
                TextBlock DescBlock = new()
                {
                    Text = itemIndex.GetSafetyChar(),
                    Foreground = "DeepWhite".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Center
                };

                Border DescBorder = new()
                {
                    Width = 25.0,
                    Height = 25.0,
                    BorderThickness = new Thickness(0),
                    CornerRadius = new CornerRadius(12),
                    Background = "RoyalSignal".FindSolidBrush(),
                    Child = DescBlock,
                    VerticalAlignment = VerticalAlignment.Center
                };

                VariantButton AddtionParaghic = new()
                {
                    MaxHeight = 35,
                    MaxWidth = 130,
                    FontSize = 15,
                    Content = "添加属性",
                    Foreground = "OverBlack".FindSolidBrush(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                VariantButton RemoveParaghic = new()
                {
                    MaxHeight = 35,
                    MaxWidth = 130,
                    FontSize = 15,
                    Content = "删除当前步骤",
                    Foreground = "OverBlack".FindSolidBrush(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                bottonGrid.SetGridWidget(0, 0, DescBorder);
                bottonGrid.SetGridWidget(0, 1, AddtionParaghic);
                bottonGrid.SetGridWidget(0, 2, RemoveParaghic);

                ConnectFlag AddtionContainer = SubscriptionKeyvaluePair.GetOrCreateValue(AddtionParaghic);
                if (!AddtionContainer.IsConnected)
                {
                    WeakEventManager<Button, MouseButtonEventArgs>.AddHandler(AddtionParaghic, nameof(Button.PreviewMouseUp), AppendTree);
                    AddtionContainer.IsConnected = true;
                }

                ConnectFlag RemoveContainer = SubscriptionKeyvaluePair.GetOrCreateValue(RemoveParaghic);
                if (!RemoveContainer.IsConnected)
                {
                    WeakEventManager<Button, MouseButtonEventArgs>.AddHandler(RemoveParaghic, nameof(Button.PreviewMouseUp), RemoveItem);
                    RemoveContainer.IsConnected = true;
                }

                ItemOutGrid.SetGridWidget(0, 0, ItemGrid);
                ItemOutGrid.SetGridWidget(1, 0, bottonGrid);

                listBoxItem.BorderThickness = new Thickness(2);
                listBoxItem.Content = ItemOutGrid;
                Items.Add(listBoxItem);
            }
        }

        private static async void AppendTree(object? sender, MouseButtonEventArgs e)
        {
            DependencyObject dependencyObject = (DependencyObject)e.Source;

            if (await dependencyObject.GetVisual<ListBoxItem>(new Server.Visual.VisualArg()
            {
                Orient = Server.Visual.VisualOrient.Bottom,
                GetFirst = true
            }) is not null and ListBoxItem _ListBoxItem
                &&
                await dependencyObject.GetVisual<MultilConfigLiBox>(new Server.Visual.VisualArg()
                {
                    Orient = Server.Visual.VisualOrient.Bottom,
                    GetFirst = true
                }) is not null and MultilConfigLiBox self)
                {
                if (await _ListBoxItem.GetVisual<ListBoxItem, Grid>(new Server.Visual.VisualArg
                {
                    Orient = Server.Visual.VisualOrient.Bottom,
                    SourceNames = [self.MainGridKey],
                    GetFirst = true
                }) is not null and Grid ItemGrid)
                {
                    self.TreeFull(ref ItemGrid,
                                  null,
                                  null,
                                  true);
                    _ListBoxItem.UpdateLayout();
                }
            }
        }

        private static void RemoveItem(object? sender, MouseButtonEventArgs e)
        {
            DependencyObject dependencyObject = (DependencyObject)e.Source;
            if (dependencyObject.FindVisualUpObject<ListBoxItem>() is not null and ListBoxItem applyItem &&
                dependencyObject.FindVisualUpObject<MultilConfigLiBox>() is not null and MultilConfigLiBox self)
            {
                self.Items.RemoveAt(self.ItemContainerGenerator.IndexFromContainer(applyItem));
            }
        }

        private void TreeFull(ref Grid layout, object? value, FieldInfo? fieldinfo, bool asolutePardon = false)
        {
            layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

            ComboBox AttributeBox = new()
            {
                FontSize = 15,
                Name = AttributeKey,
                FontFamily = "KaiTi".FindSource<FontFamily>(),
                ItemsSource = ActivityAssistBehivor.Behivor.AttributeTranslationMap.Values,
                Margin = new Thickness(0, 8, 0, 8),
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch
            };

            ComboBox IdeaValueBox = new()
            {
                FontSize = 15,
                IsEditable = true,
                Name = MapTValueKey,
                FontFamily = "KaiTi".FindSource<FontFamily>(),
                Margin = new Thickness(0, 8, 10, 8),
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalContentAlignment = HorizontalAlignment.Stretch
            };

            TextBlock TakeTextBlock = new()
            {
                Text = "\ue61b",
                Name = MapTValueKey,
                FontFamily = "Icon".FindSource<FontFamily>(),
                FontSize = 20.0,
                Foreground = "SunsetCoral".FindSolidBrush(),
                Margin = new Thickness(10, 8, 0, 8),
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Center
            };

            ConnectFlag AtrributeBoxConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(AttributeBox);
            if (!AtrributeBoxConnectFlag.IsConnected)
            {
                WeakEventManager<ComboBox, SelectionChangedEventArgs>.AddHandler(AttributeBox, nameof(ComboBox.SelectionChanged), ValueOptionsChange);
                AtrributeBoxConnectFlag.IsConnected = true;
            }

            ConnectFlag IdeaValueBoxConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(IdeaValueBox);
            if (!IdeaValueBoxConnectFlag.IsConnected)
            {
                WeakEventManager<ComboBox, RoutedEventArgs>.AddHandler(IdeaValueBox, nameof(ComboBox.GotFocus), ValueMonitoring);
                IdeaValueBoxConnectFlag.IsConnected = true;
            }

            ConnectFlag TakeBlockConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(TakeTextBlock);
            if (!TakeBlockConnectFlag.IsConnected)
            {
                WeakEventManager<TextBlock, MouseButtonEventArgs>.AddHandler(TakeTextBlock, nameof(TextBlock.PreviewMouseDown), TakeTree);
                TakeBlockConnectFlag.IsConnected = true;
            }

            if (!asolutePardon)
            {
                if (fieldinfo is not null && ActivityAssistBehivor.Behivor.AttributeTranslationMap.TryGetValue(fieldinfo.Name, out string? translations))
                {
                    AttributeBox.Text = translations;
                    ValidAtrributes.Add(translations);
                }

                if (fieldinfo is not null && ActivityAssistBehivor.Behivor.AttributePrimaryMap.TryGetValue(fieldinfo.Name, out bool primary) && primary)
                {
                    AttributeBox.IsEnabled = !primary;
                    TakeTextBlock.Visibility = Visibility.Collapsed;
                }

                if (fieldinfo is not null)
                {
                    string key = fieldinfo.Name;
                    List<string> exepcts = [];
                    if (new List<string> { "Step", "Command" }.Contains(key))
                    {
                        foreach (var kvp in ActivityAssistBehivor.Behivor.ProductFlagChzMap)
                        {
                            if (ActivityAssistBehivor.Behivor.AttributeConfigProductType.Contains(kvp.Value))
                            {
                                key += $"-{kvp.Key}";
                            }
                        }
                    }
       
                    if (ActivityAssistBehivor.Behivor.AttributeExpectsMap.TryGetValue(key, out List<string>? _exepcts))
                    {
                        exepcts = _exepcts;
                        IdeaValueBox.ItemsSource = exepcts;
                    }
                }

                if (value is not null)
                {
                    IdeaValueBox.Text = value.GetSafetyChar();
                }
            }

            layout.SetGridWidget(layout.RowDefinitions.Count - 1, 0, AttributeBox);
            layout.SetGridWidget(layout.RowDefinitions.Count - 1, 1, IdeaValueBox);
            layout.SetGridWidget(layout.RowDefinitions.Count - 1, 2, TakeTextBlock);
        }

        private async static void ValueMonitoring(object? sender, RoutedEventArgs args)
        {
            if (sender is not null and ComboBox valueCombobox)
            {
                if (await valueCombobox.GetVisual<MultilConfigLiBox>(new Server.Visual.VisualArg
                {
                    Orient = Server.Visual.VisualOrient.Top,
                    GetFirst = true
                }) is not null and MultilConfigLiBox self)
                {
                    await valueCombobox.Dispatcher.InvokeAsync(async () =>
                    {
                        if (sender is not null && sender is ComboBox IdeaValueBox)
                        {
                            if (await IdeaValueBox.GetVisual<ComboBox, TextBox>(new Server.Visual.VisualArg
                            {
                                GetFirst = true,
                                SourceNames = ["PART_EditableTextBox"]
                            }) is not null and TextBox _TextBox) 
                            {
                                ConnectFlag IdeaValueBoxConnectFlag = self.SubscriptionKeyvaluePair.GetOrCreateValue(_TextBox);
                                if (!IdeaValueBoxConnectFlag.IsConnected)
                                {
                                    WeakEventManager<TextBox, TextChangedEventArgs>.AddHandler(_TextBox, nameof(TextBox.TextChanged), ValueChange);
                                    IdeaValueBoxConnectFlag.IsConnected = true;
                                }
                            }
                        }
                    }, DispatcherPriority.Background);
                }
            }
        }

        private static void ValueOptionsChange(object? sender, SelectionChangedEventArgs e)
        {
            Application.Current.Dispatcher.InvokeAsync(async () =>
            {
                if (sender is not null and ComboBox _Combobox)
                {
                    object? _self_ = await _Combobox.GetVisual<MultilConfigLiBox>(
                    new Server.Visual.VisualArg
                    {
                        GetFirst = true,
                        Orient = Server.Visual.VisualOrient.Top
                    });

                    if (_self_ is not null and MultilConfigLiBox self &&
                        _Combobox.Name == self.AttributeKey &&
                        e.Source is DependencyObject _SourceDependency)
                    {
                        object? _ContnetGrid_ = await _SourceDependency.GetVisual<Grid>(new Server.Visual.VisualArg
                        {
                            Orient = Server.Visual.VisualOrient.Top,
                            GetFirst = true
                        });

                        if (_ContnetGrid_ is not null and Grid _mainGrid)
                        {
                            object? _Listboxitem_ = await _SourceDependency.GetVisual<ListBoxItem>(new Server.Visual.VisualArg
                            {
                                Orient = Server.Visual.VisualOrient.Top,
                                GetFirst = true
                            });

                            if (_Listboxitem_ is not null and ListBoxItem _ListBoxItem)
                            {
                                try
                                {
                                    int currentIndex = Grid.GetRow(_Combobox);
                                    ICollection<UIElement> unitRow = _mainGrid.GetGridRowWidget(currentIndex);

                                    foreach (var uiCom in unitRow)
                                    {
                                        if (uiCom is ComboBox comboBox &&
                                            comboBox.Name == self.MapTValueKey)
                                        {
                                            ComboBox valueComboBox = comboBox;
                                            if (_Combobox.Text is not null and string _Combobox_Echo_Text &&
                                                ActivityAssistBehivor.Behivor.AttributeTranslationMap.GetSafetyKey<string, string>(_Combobox_Echo_Text) is not null and
                                                ICollection<string> keys && keys.Count == 1)
                                            {
                                                string key = keys.ElementAt(0);

                                                List<string> exepcts = [];

                                                if (new List<string> { nameof(TestItemDeepSeatedSealed.Step), nameof(TestItemDeepSeatedSealed.Command) }.Contains(key))
                                                {
                                                    foreach (var kvp in ActivityAssistBehivor.Behivor.ProductFlagChzMap)
                                                    {
                                                        if (ActivityAssistBehivor.Behivor.AttributeConfigProductType.Contains(kvp.Value))
                                                        {
                                                            key += $"-{kvp.Key}";
                                                            break;
                                                        }
                                                    }
                                                }

                                                if (ActivityAssistBehivor.Behivor.AttributeExpectsMap.TryGetValue(key, out List<string>? _exepcts))
                                                {
                                                    comboBox.ItemsSource = _exepcts;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception error)
                                {
                                    self?.Logger.Error(error.Message);
                                }
                            }
                        }
                    }
                }
            }, DispatcherPriority.Background);
        

        }

        // 监控值变化，是否预期
        private static void ValueChange(object? sender, TextChangedEventArgs e)
        {
            if (sender is not null)
            {
                TextBox _TextBox = (TextBox)sender;

                _TextBox.Dispatcher.InvokeAsync(async () =>
                {
           
                    if (await _TextBox.GetVisual<MultilConfigLiBox>(new Server.Visual.VisualArg
                    {
                        Orient = Server.Visual.VisualOrient.Top,
                        GetFirst = true
                    }) is not null and MultilConfigLiBox self)
                    {
                        try
                        {
                            if (await _TextBox.GetVisual<ComboBox>(new Server.Visual.VisualArg
                            {
                                Orient = Server.Visual.VisualOrient.Top,
                                GetFirst = true
                            }) is not null and ComboBox TxcomBox)
                            {
                                if (await TxcomBox.GetVisual<Grid>(new Server.Visual.VisualArg
                                {
                                    Orient = Server.Visual.VisualOrient.Top,
                                    GetFirst = true,
                                    SourceNames = [self.MainGridKey]
                                }) is not null and Grid mainLayoutGrid)
                                {
                                    if (mainLayoutGrid.GetGridRowWidget(Grid.GetRow(TxcomBox)).GetWidget<ComboBox>(self.AttributeKey) is not null and ComboBox AtrributeBox)
                                    {
                                        ICollection<string>? TranslationText = ActivityAssistBehivor.Behivor.AttributeTranslationMap.GetSafetyKey(AtrributeBox.Text);

                                        if (TranslationText is not null && TranslationText.Count == 1)
                                        {
                                            FieldInfo? field = new TestItemDeepSeatedSealed(string.Empty).GetField(TranslationText.ElementAt(0));

                                            if (field is not null && await TxcomBox.GetVisual<Border>(
                                                new Server.Visual.VisualArg
                                                {
                                                    Orient = Server.Visual.VisualOrient.Bottom,
                                                    GetFirst = true
                                                }) is not null and Border TxBoxBorder)
                                            {
                                                if (field.CanSafetyConvert(_TextBox.Text, out object? value))
                                                {
                                                    if (TxBoxBorder is not null)
                                                    {
                                                        TxBoxBorder.BorderBrush = SystemColors.ControlDarkBrush;
                                                        TxBoxBorder.BorderThickness = new Thickness(1);
                                                    }
                                                }
                                                else
                                                {
                                                    if (TxBoxBorder is not null)
                                                    {
                                                        TxBoxBorder.BorderBrush = "SunsetCoral".FindSolidBrush();
                                                        TxBoxBorder.BorderThickness = new Thickness(1);
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception error)
                        {
                            self?.Logger.Debug(error.Message);
                        }
                    }
                });
            }
        }

        private async static void TakeTree(object? sender, MouseButtonEventArgs e)
        {
            if (sender is not null &&
                sender is TextBlock TakeUnit &&
                await TakeUnit.GetVisual<MultilConfigLiBox>(new Server.Visual.VisualArg
                {
                    Orient = Server.Visual.VisualOrient.Top,
                    GetFirst = true
                }) is not null and MultilConfigLiBox self &&

                 await TakeUnit.GetVisual<ListBoxItem>(new Server.Visual.VisualArg
                 {
                     Orient = Server.Visual.VisualOrient.Top,
                     GetFirst = true
                 }) is not null and ListBoxItem listBoxitem &&
                listBoxitem.Content is Grid mainGrid)
            {
                if (await mainGrid.GetVisual<Grid>(new Server.Visual.VisualArg
                {
                    GetFirst = true,
                    SourceNames = [self.MainGridKey]
                }) is not null and Grid ContentGrid)

                await TakeUnit.Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        int DelRow = Grid.GetRow(TakeUnit);
                        ContentGrid.TakeGridRowWidget(DelRow);
                        
                    } 
                    catch (Exception error)
                    {
                        self.Logger.Print(RuntimeLog.LogType.Debug, $"attribute line remove encount error: {error.Message}");
                    }
                });

            }
        }

        private static void CompleteLoaded(object? sender, RoutedEventArgs e)
        {
            if (sender is not null and MultilConfigLiBox self)
            {
                self.Ashbin = new Ruined(self, () =>
                {
                    foreach (var kvp in self.SubscriptionKeyvaluePair)
                    {
                        if (kvp.Key is TextBlock _TextBlock && _TextBlock.Name == self.MapTValueKey)
                        {
                            WeakEventManager<TextBlock, MouseButtonEventArgs>.RemoveHandler(_TextBlock, nameof(TextBlock.PreviewMouseDown), TakeTree);
                        }
                        else if (kvp.Key is ComboBox _ComboBox1 && _ComboBox1.Name == self.MapTValueKey)
                        {
                            WeakEventManager<ComboBox, RoutedEventArgs>.RemoveHandler(_ComboBox1, nameof(ComboBox.GotFocus), ValueMonitoring);

                            if (_ComboBox1.FindNestVisualTreeObject<TextBox>("PART_EditableTextBox") is not null and TextBox valueTextBox)
                            {
                                WeakEventManager<TextBox, TextChangedEventArgs>.RemoveHandler(valueTextBox, nameof(TextBox.TextChanged), ValueChange);
                            }
                        }
                        else if (kvp.Key is ComboBox _ComboBox2 && _ComboBox2.Name == self.AttributeKey)
                        {
                            WeakEventManager<ComboBox, SelectionChangedEventArgs>.RemoveHandler(_ComboBox2, nameof(ComboBox.SelectionChanged), ValueOptionsChange);
                        }
                    }
                    self.SubscriptionKeyvaluePair.Clear();
                    self.Ashbin = null;
                    WeakEventManager<MultilConfigLiBox, RoutedEventArgs>.RemoveHandler(self, nameof(Loaded), CompleteLoaded);
                });
            }
        }

        public MultilConfigLiBox()
        {
            if ("ListBoxTemplate".FindSource<Style>() is not null and Style style) Style = style;

            WeakEventManager<MultilConfigLiBox, RoutedEventArgs>.AddHandler(this, nameof(Loaded), CompleteLoaded);
            ScrollViewer.SetVerticalScrollBarVisibility(this, ScrollBarVisibility.Auto);
        }
    }

    public class SignalConfigLiBox : ListBox, IDisposable
    {
        private static readonly ILogger Logger = Log.ForContext<SignalConfigLiBox>();
        private readonly static SemaphoreSlim Semaphore = new(1, 1);
        private readonly string MapTKey = "combobox_key";
        private readonly string MapTValue = "combobox_value";
        private readonly string Empty = "无";
        private ICollection<string> ConsultColumnNames = [];
        private Dictionary<string, string> ConsultMapdetail = [];
        private readonly List<string> TranslationFieldNames = [];
        private static readonly ConditionalWeakTable<UIElement, ConnectFlag> SubscriptionKeyvaluePair = [];

        public ICommand CmdContentPushCommand
        {
            set
            {
                SetValue(ContentPushCommandProperty, value);
            }
            get
            {
                return (ICommand)GetValue(ContentPushCommandProperty);
            }
        }

        public Deserted Options
        {
            set
            {
                SetValue(OptionsProperty, value);
            }
            get
            {
                return (Deserted)GetValue(OptionsProperty);
            }
        }

        private static readonly DependencyProperty ContentPushCommandProperty = DependencyProperty.Register(
            nameof(CmdContentPushCommand),
            typeof(ICommand),
            typeof(SignalConfigLiBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty OptionsProperty = DependencyProperty.Register(
             nameof(Options),
             typeof(Deserted),
             typeof(SignalConfigLiBox),
             new PropertyMetadata(null, OptionChangedCallback));

        private static void OptionChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is SignalConfigLiBox self)
            {
                if (e.OldValue is Deserted _OldOptions)
                {
                    _OldOptions.PropertyChanged -= self.OptionsChangeEvent;
                }
                if (e.NewValue is Deserted _NewOptions)
                {
                    _NewOptions.PropertyChanged += self.OptionsChangeEvent;
                }
            }
        }

        private void OptionsChangeEvent(object? sender, PropertyChangedEventArgs e)
        {
            if (sender is not null and Deserted Options)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (Options.CapCTDBfieldConfig)
                    {
                        ArrestDBReserveMapGroup();
                        Options.CapCTDBfieldConfig = !Options.CapCTDBfieldConfig;
                    }
                    if (Options.IFLoadDBMapInfoPush is not null and KeyValuePair<Dictionary<string, string>, ICollection<string>> MapInfo)
                    {
                        GetInitializeDatas(MapInfo);
                        Options.IFLoadDBMapInfoPush = null;
                    }
                });
            }
        }

        public SignalConfigLiBox()
        {
            if ("ListBoxTemplate".FindSource<Style>() is not null and Style style)
            {
                Style = style;
            }
            TranslationFieldNames = [.. ActivityAssistBehivor.Behivor.DBReserveDutyTranslationMap.Values];

            Unloaded += NoloadedEvent;
        }

        private void NoloadedEvent(object sender, RoutedEventArgs e)
        {
            WeakReferenceMessenger.Default.Unregister<MvvmMessage>(this);
            Unloaded -= NoloadedEvent;
        }

        public void GetInitializeDatas(KeyValuePair<Dictionary<string, string>, ICollection<string>> MapInfo)
        {
            Dispatcher.Invoke(async () =>
            {
                ConsultColumnNames = MapInfo.Value;

                if (!ConsultColumnNames.Contains(Empty)) ConsultColumnNames.Add(Empty);

                ConsultMapdetail = MapInfo.Key;

                bool canSemaphore = await Semaphore.WaitAsync(3000);

                if (canSemaphore)
                {
                    if (Items.Count >= 1)
                    {
                        ShallowLoader();
                    }
                    else
                    {
                        await DataCollectionChange();
                    }
                }
            });
        }

        public async void ArrestDBReserveMapGroup()
        {
            await Task.Run(() =>
            {
                Dispatcher.Invoke(() =>
                {
                    Dictionary<string, string> TreamslationCombination = [];
                    foreach (ListBoxItem item in Items)
                    {
                        if (item.Content is Grid mainGrid)
                        {
                            for (int mrow = 0; mrow < mainGrid.RowDefinitions.Count; mrow++)
                            {
                                var ComponentPair = mainGrid.GetGridRowPairWidget<TextBlock, ComboBox>(mrow, MapTKey, MapTValue);


                                if (ComponentPair.HasValue)
                                {
                                    string RealKey = ComponentPair.Value.Key.Text;
                                    string RealValue = ComponentPair.Value.Value.Text;
                                    if (ActivityAssistBehivor.Behivor.DBReserveDutyTranslationMap.GetSafetyKey<string, string>(RealKey) is not null and 
                                        ICollection<string> transla && transla.Count == 1 &&
                                        !string.IsNullOrEmpty(RealValue))
                                    {
                                        TreamslationCombination.Add(transla.ElementAt(0), RealValue);
                                    }
                                }
                            }
                        }
                    }
                    CmdContentPushCommand.Execute(TreamslationCombination);
                });
            });
        }

        //  浅加载，不创建组件，仅加载数据
        public async void ShallowLoader()
        {
            await Dispatcher.InvokeAsync(() =>
            {
                Dictionary<string, string> TreamslationCombination = [];
                //  遍历ITEM
                foreach (ListBoxItem item in Items)
                {
                    //  遍历所有主布局
                    if (item.Content is Grid mainGrid)
                    {
                        //  遍历布局每行
                        for (int mrow = 0; mrow < mainGrid.RowDefinitions.Count; mrow++)
                        {
                            //  查找每行中的提示组件和选择组件
                            var ComponentPair = mainGrid.GetGridRowPairWidget<TextBlock, ComboBox>(mrow, MapTKey, MapTValue);

                            if (ComponentPair is not null)
                            {
                                //  提取组件
                                TextBlock TranslationBlock = ComponentPair.Value.Key;

                                ComboBox IdeaColumnBox = ComponentPair.Value.Value;

                                //  将详情字典中的数据加载至组件中
                                if (ConsultMapdetail.Count > 0)
                                {
                                    //  获取提示组件文本，通过文本对应至非中文key，通过key值获取详情value值，把value值赋值给下拉组件作为显示文本
                                    if (ActivityAssistBehivor.Behivor.DBReserveDutyTranslationMap.GetSafetyKey(TranslationBlock.Text) is not null and
                                        ICollection<string> keys && keys.Count == 1 &&
                                        ConsultMapdetail.TryGetValue(keys.ElementAt(0), out string? value) && IdeaColumnBox is not null)
                                    {
                                        IdeaColumnBox.ItemsSource = ConsultColumnNames;
                                        IdeaColumnBox.Text = value;
                                    }
                                }
                            }
                        }
                    }
                }
                Semaphore.Release();
            });
        }

        //  创建组件，也加载数据,该方法创建大体框架，由 TreeFull 创建细节项
        public async Task DataCollectionChange()
        {
            await Application.Current.Dispatcher.InvokeAsync(async () =>
            {
                int row = 0;
                Grid ItemGrid = new()
                {
                    VerticalAlignment = VerticalAlignment.Stretch,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(3, GridUnitType.Star) });
                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(7, GridUnitType.Star) });

                ListBoxItem listBoxItem = new()
                {
                    Margin = new Thickness(5),
                    BorderThickness = new Thickness(4),
                    HorizontalContentAlignment = HorizontalAlignment.Stretch,
                    VerticalContentAlignment = VerticalAlignment.Stretch
                };

                if ("DynamicListBoxItemControl".FindSource<ControlTemplate>() is not null and ControlTemplate template) listBoxItem.Template = template;

                listBoxItem.BorderBrush = "RoyalSignal".FindSolidBrush();

                if (Items.Count == 0)
                {
                    foreach (string translation in TranslationFieldNames)
                    {
                        await TreeFull(ItemGrid, translation);
                        row++;
                    }

                    listBoxItem.BorderThickness = new Thickness(2);
                    listBoxItem.Content = ItemGrid;
                    Items.Add(listBoxItem);
                }
                Semaphore.Release();
            }, DispatcherPriority.Background);
        }

        public async Task TreeFull(Grid layout, string translation)
        {
            await Dispatcher.InvokeAsync(() =>
            {
                layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                TextBlock TranslationName = new()
                {
                    Text = translation,
                    FontSize = 15,
                    Name = MapTKey,
                    FontFamily = "KaiTi".FindSource<FontFamily>(),
                    Margin = new Thickness(4, 6, 4, 6),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                ComboBox IdeaColumnBox = new()
                {
                    FontSize = 15,
                    IsEditable = true,
                    Name = MapTValue,
                    FontFamily = "KaiTi".FindSource<FontFamily>(),
                    ItemsSource = ConsultColumnNames,
                    Margin = new Thickness(4, 6, 4, 6),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    HorizontalContentAlignment = HorizontalAlignment.Stretch
                };

                if (ConsultMapdetail.Count > 0)
                {
                    if (ActivityAssistBehivor.Behivor.DBReserveDutyTranslationMap.GetSafetyKey(translation) is not null and ICollection<string> keys &&
                        keys.Count == 1 &&
                        ConsultMapdetail.TryGetValue(keys.ElementAt(0), out string? value))
                    {
                        IdeaColumnBox.Text = value;
                    }
                }

                ConnectFlag AtrributeBoxConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(IdeaColumnBox);
                if (!AtrributeBoxConnectFlag.IsConnected)
                {
                    WeakEventManager<ComboBox, EventArgs>.AddHandler(IdeaColumnBox, nameof(ComboBox.DropDownOpened), ComboboxItemsChange);
                    AtrributeBoxConnectFlag.IsConnected = true;
                }

                layout.SetGridWidget(layout.RowDefinitions.Count - 1, 0, TranslationName);
                layout.SetGridWidget(layout.RowDefinitions.Count - 1, 1, IdeaColumnBox);
            }, DispatcherPriority.DataBind);
        }

        private async static void ComboboxItemsChange(object? sender, EventArgs args)
        {
            if (sender is not null and ComboBox _Combobox)
            {
                await _Combobox.Dispatcher.InvokeAsync(async () =>
                {
                    string Privious = _Combobox.Text;
                    SignalConfigLiBox? self = _Combobox.FindVisualUpObject<SignalConfigLiBox>();

                    //  获取所有下拉框默认文本
                    List<string> allComboboxText = [.. _Combobox.FindVisualUpObjects<Grid, ComboBox>().Select(x => x.Text)];

                    if (self is not null)
                    {
                        List<string> suplusTrans = [.. self.ConsultColumnNames.Where(x => !allComboboxText.Contains(x))];

                        if (!suplusTrans.Contains(self.Empty)) suplusTrans.Add(self.Empty);
                        _Combobox.ItemsSource = suplusTrans;
                    }

                    await Task.Delay(120);

                    _Combobox.Text = Privious;

                });
            }
        }

        private readonly object _syncobj = new();

        public bool _disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            Dispatcher.Invoke(() =>
            {
                bool _synclock = false;
                try
                {
                    if (!_disposed)
                    {
                        Monitor.Enter(_syncobj, ref _synclock);
                        _disposed = true;
                    }
                }
                finally
                {
                    Logger.Debug($"{this} -> release, where lock stat {_synclock}");
                    if (_synclock) Monitor.Exit(_syncobj);
                }
            });
        }

        ~SignalConfigLiBox()
        {
            Dispose(false);
        }

        private void OnLoader(object? sender, RoutedEventArgs e)
        {
            Dispose();
        }
    }

    public class KeyValuePairLiBox : ListBox, IDisposable
    {
        private static readonly ILogger Logger = Log.ForContext<KeyValuePairLiBox>();
        private readonly string LayoutTKey = "Name_MainLayoutKey";
        private readonly string MapTKey = "Name_01Key";
        private ICollection<KvpGroup> ConsultMapdetail = [];
        private readonly ConditionalWeakTable<FrameworkElement, ConnectFlag> SubscriptionKeyvaluePair = [];
        private Ruined? Ashbin = null;
        private readonly double RowHright = 38;

        public KeyValuePairLiBox()
        {
            if ("ListBoxTemplate".FindSource<Style>() is not null and Style style)
            {
                Style = style;
            }
            Loaded += CompleteLoaded;
        }

        public ICommand CmdMesMapInfo
        {
            set
            {
                SetValue(MesMapInfoCommandProperty, value);
            }
            get
            {
                return (ICommand)GetValue(MesMapInfoCommandProperty);
            }
        }

        public ICommand CmdMesMapExit
        {
            set
            {
                SetValue(MesMapExitCommandProperty, value);
            }
            get
            {
                return (ICommand)GetValue(MesMapExitCommandProperty);
            }
        }

        public Deserted Options
        {
            set
            {
                SetValue(OptionsProperty, value);
            }
            get
            {
                return (Deserted)GetValue(OptionsProperty);
            }
        }

        private static readonly DependencyProperty MesMapInfoCommandProperty = DependencyProperty.Register(
            nameof(CmdMesMapInfo),
            typeof(ICommand),
            typeof(KeyValuePairLiBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty MesMapExitCommandProperty = DependencyProperty.Register(
            nameof(CmdMesMapExit),
            typeof(ICommand),
            typeof(KeyValuePairLiBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty OptionsProperty = DependencyProperty.Register(
             nameof(Options),
             typeof(Deserted),
             typeof(KeyValuePairLiBox),
             new PropertyMetadata(null, OptionChangedCallback));

        private static void OptionChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is KeyValuePairLiBox self)
            {
                if (e.OldValue is Deserted _OldOptions)
                {
                    _OldOptions.PropertyChanged -= self.OptionsChangeEvent;
                }
                if (e.NewValue is Deserted _NewOptions)
                {
                    _NewOptions.PropertyChanged += self.OptionsChangeEvent;
                }
            }
        }

        public void OptionsChangeEvent(object? sender, PropertyChangedEventArgs e)
        {
            if (sender is not null and Deserted Options)
            {
                if (Options.IFLoadMesMapInfoPush is not null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        InitializeDatas(Options.IFLoadMesMapInfoPush);
                        Options.IFLoadMesMapInfoPush = null;

                    });
                };
            }
        }

        public void InitializeDatas(object? param)
        {
            Dispatcher.Invoke(async () =>
            {
                if (param is not null and ICollection<KvpGroup> data)
                {
                    ConsultMapdetail = data;
                    if (Items.Count >= 1)
                    {
                        ShallowLoader();
                    }
                    else
                    {
                        await UILoader();
                    }
                }
            });
        }

        public void CapTrue(object sender, MouseButtonEventArgs e)
        {
            Dispatcher.InvokeAsync(() =>
            {
                ICollection<KvpGroup> MesMapColletion = [];
                foreach (ListBoxItem item in Items)
                {
                    if (item.Content is Grid mainGrid)
                    {
                        IEnumerable<Grid> itemGrids = mainGrid.FindVisualUpObjects<Grid, Grid>().Where(x => x.Name == LayoutTKey);

                        foreach (var itemGrid in itemGrids)
                        {
                            for (int mrow = 0; mrow < itemGrid.RowDefinitions.Count; mrow++)
                            {
                                List<KvpGroup.Sec> Secs = [];

                                foreach (var unit in itemGrid.Children.OfType<FrameworkElement>().Where(unit => Grid.GetRow(unit) == mrow))
                                {
                                    KvpGroup.Sec sec = new ();

                                    string content = string.Empty;

                                    string name = string.Empty;

                                    List<string> selects = [];

                                    if (unit is TextBlock _TextBlock && !string.IsNullOrEmpty(_TextBlock.Name))
                                    {
                                        content = _TextBlock.Text;
                                        name = _TextBlock.Name;
                                    }
                                    else if (unit is ComboBox _ComboBox)
                                    {
                                        content = _ComboBox.Text;
                                        name = _ComboBox.Name;
                                        if (_ComboBox.ItemsSource is List<string> _ItemsSource) selects.AddRange(_ItemsSource);


                                    }
                                    else if (unit is TextBox _TextBox)
                                    {
                                        content = _TextBox.Text;
                                        name = _TextBox.Name;
                                    }

                                    sec.Content = content;
                                    sec.WidgetType = unit.GetType().Name;
                                    sec.Flag = name;
                                    sec.Selects = selects;
                                    Secs.Add(sec);
                                }

                                if (Secs.Count > 0 && Secs.Where(x => x.Flag.IsAbsoluteValidValue()).Any())
                                {
                                    MesMapColletion.Add(new KvpGroup
                                    {
                                        SHowyDatas = Secs
                                    });
                                }
                            }
                        }
                    }
                }
                CmdMesMapInfo.Execute(MesMapColletion);
            });
        }

        public void Addtion(object sender, MouseButtonEventArgs e)
        {
            if (sender is VariantButton _Button)
            {
                this.Dispatcher.InvokeAsync( async () =>
                {
                    if (await _Button.GetVisual<Grid>(new Server.Visual.VisualArg
                    {
                        Orient = Server.Visual.VisualOrient.Top,
                        SourceNames = [LayoutTKey]
                    }) is not null and Grid ItemGrid)
                    {
                        int RowCount = ItemGrid.RowDefinitions.Count;

                        List<(string, string, string)> NewConfig = 
                        [
                            ("未定义", nameof(EnjoyCombobox), "TestProcessName"),
                            ("未定义", nameof(EnjoyCombobox), "MesProcessName"),
                            ("未定义", nameof(EnjoyCombobox), "MesStationName"),
                            (string.Empty, nameof(EnjoyCombobox), "MesBingDingType"),
                        ];

                        await TreeFull(ItemGrid, new KvpGroup
                        {
                            SHowyDatas = [.. NewConfig.Select(x=> new KvpGroup.Sec
                            {
                                Content = x.Item1,
                                WidgetType = x.Item2,
                                Flag = x.Item3
                            })]
                        }, RowCount);
                    }
                });
            }
        }

        public void Take(object sender, MouseButtonEventArgs e)
        {
            if (sender is Border _Border)
            {
                this.Dispatcher.InvokeAsync(async () =>
                {
                    object? GridObject = await Server.Visual.GetVisual<Grid>(_Border, new Server.Visual.VisualArg
                    {
                        Orient = Server.Visual.VisualOrient.Top,
                        SourceNames = [LayoutTKey]
                    });

                    if (GridObject is not null and Grid MainGrid)
                    {
                        MainGrid.TakeGridRowWidget(Grid.GetRow(_Border));
                    }
                });
            }
        }

        public void Exit(object sender, MouseButtonEventArgs e)
        {
            CmdMesMapExit.Execute(null);
        }

        //  浅加载，不创建组件，仅加载数据
        public async void ShallowLoader()
        {
            await Dispatcher.InvokeAsync(() =>
            {
                KvpGroup.Sec? GetSec(string key)
                {
                    foreach (var group in ConsultMapdetail)
                    {
                        foreach (var sec in group.SHowyDatas)
                        {
                            if (key == sec.Flag)
                            {
                                return sec;
                            }
                        }
                    }
                    return null;
                }

                Dictionary<string, string> TreamslationCombination = [];
                //  遍历ITEM
                foreach (ListBoxItem item in Items)
                {
                    //  遍历所有主布局
                    if (item.Content is Grid mainGrid)
                    {
                        IEnumerable<Grid> itemGrids = mainGrid.FindVisualUpObjects<Grid, Grid>().Where(x => x.Name == MapTKey);

                        foreach (var itemGrid in itemGrids)
                        {
                            //  遍历布局每行
                            for (int mrow = 0; mrow < mainGrid.RowDefinitions.Count; mrow++)
                            {
                                foreach (var unit in itemGrid.Children.OfType<FrameworkElement>().Where(unit => Grid.GetRow(unit) == mrow))
                                {
                                    string name = string.Empty;

                                    if (unit is TextBlock _TextBlock && 
                                        !string.IsNullOrEmpty(_TextBlock.Name))
                                    {
                                        KvpGroup.Sec? _Sec = GetSec(_TextBlock.Name);
                                        if (_Sec is not null)
                                        {
                                            _TextBlock.Text = _Sec.Content;
                                            _TextBlock.Name = _Sec.Flag;
                                        }
                                    }
                                    else if (unit is ComboBox _ComboBox)
                                    {
                                        KvpGroup.Sec? _Sec = GetSec(_ComboBox.Name);
                                        if (_Sec is not null)
                                        {
                                            _ComboBox.Text = _Sec.Content;
                                            _ComboBox.SelectedValue = _Sec.Content;
                                            _ComboBox.Name = _Sec.Flag;
                                        }
                                    }
                                    else if (unit is TextBox _TextBox)
                                    {
                                        KvpGroup.Sec? _Sec = GetSec(_TextBox.Name);
                                        if (_Sec is not null)
                                        {
                                            _TextBox.Text = _Sec.Content;
                                            _TextBox.Name = _Sec.Flag;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }

        //  创建组件，也加载数据,该方法创建大体框架，由 TreeFull 创建细节项
        public async Task UILoader()
        {
            await Application.Current.Dispatcher.InvokeAsync(async () =>
            {
                Grid MainGrid = new ();
                MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(38) });

                Grid ItemGrid = new()
                {
                    Name = LayoutTKey,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) });
                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Star) });
                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Star) });
                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) });
                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(RowHright) });

                UniformGrid BottonUnifGrid = new ()
                {
                    Columns = 3,
                    Margin = new Thickness(0, 5, 0, 4)
                };

                ListBoxItem listBoxItem = new()
                {
                    Margin = new Thickness(5),
                    BorderThickness = new Thickness(4),
                    HorizontalContentAlignment = HorizontalAlignment.Stretch,
                    VerticalContentAlignment = VerticalAlignment.Stretch
                };
                if ("DynamicListBoxItemControl".FindSource<ControlTemplate>() is not null and ControlTemplate template) listBoxItem.Template = template;

                List<(string, string, MouseButtonEventHandler)> Buttoms =
                [
                    ("保存", "SaveButton", CapTrue) ,
                    ("新增", "AddButton", Addtion) ,
                    ("退出", "ExitButton", Exit) ,
                ];

                foreach(var buttom in Buttoms)
                {
                    VariantButton VarButtom = new()
                    {
                        MaxHeight = 27,
                        MaxWidth = 130,
                        FontSize = 15,
                        Content = buttom.Item1,
                        Name = buttom.Item2,
                        Foreground = "OverBlack".FindSolidBrush(),
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        VerticalAlignment = VerticalAlignment.Stretch
                    };

                    VarButtom.PreviewMouseUp += buttom.Item3;

                    ConnectFlag Flag = SubscriptionKeyvaluePair.GetOrCreateValue(VarButtom);
                    if (!Flag.IsConnected) Flag.IsConnected = true;

                    BottonUnifGrid.Children.Add(VarButtom);
                }

                if (Items.Count == 0)
                {
                    int row = 0;
                    foreach (var mesMap in ConsultMapdetail)
                    {
                        await TreeFull(ItemGrid, mesMap, row);

                        row++;
                    }

                    MainGrid.SetGridWidget(0, 0, ItemGrid);
                    MainGrid.SetGridWidget(1, 0, BottonUnifGrid);

                    listBoxItem.BorderBrush = Brushes.Transparent;
                    listBoxItem.BorderThickness = new Thickness(2);
                    listBoxItem.Content = MainGrid;
                    Items.Add(listBoxItem);
                }

            }, DispatcherPriority.Background);
        }

        public async Task TreeFull(Grid layout, KvpGroup _KvpGroup, int row)
        {
            static FrameworkElement GetWidget(KvpGroup.Sec sec)
            {               
                FrameworkElement _WidgetType = new Border();

                if (sec.WidgetType == nameof(TextBlock))
                {
                    _WidgetType = new TextBlock()
                    {
                        Text = sec.Content,
                        Name = sec.Flag,
                        FontSize = 14,
                        MinHeight = 30,
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        Margin = new Thickness(2, 3, 2, 3),
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Stretch
                    };
                }
                else if (sec.WidgetType == nameof(TextBox) || sec.WidgetType == nameof(EnjoyTextBox))
                {
                    _WidgetType = new EnjoyTextBox()
                    {
                        Text = sec.Content,
                        FontSize = 14,
                        Name = sec.Flag,
                        MinHeight = 30,
                        CornerRadius = new CornerRadius(4),
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        Margin = new Thickness(2, 3, 2, 3),
                        Background = "DeepWhite".FindSolidBrush(),
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        VerticalAlignment = VerticalAlignment.Stretch,
                        HorizontalContentAlignment = HorizontalAlignment.Center,
                        VerticalContentAlignment = VerticalAlignment.Center
                    };
                }
                else if (sec.WidgetType == nameof(ComboBox) || sec.WidgetType == nameof(EnjoyCombobox))
                {
                    _WidgetType = new EnjoyCombobox()
                    {
                        Text = sec.Content,
                        FontSize = 14,
                        MinHeight = 30,
                        Name = sec.Flag,
                        MinWidth = 140,
                        SelectedValue = sec.Content,
                        ItemsSource = sec.Selects is not null && sec.Selects.Count > 0 ? sec.Selects : [],
                        Background = "DeepWhite".FindSolidBrush(),
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        Margin = new Thickness(2, 3, 2, 3),
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Stretch,
                        HorizontalContentAlignment = HorizontalAlignment.Center,
                        VerticalContentAlignment = VerticalAlignment.Center
                    };
                }
                return _WidgetType;
            }

            await Dispatcher.InvokeAsync(() =>
            {
                layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(RowHright) });

                int column = 0;

                foreach (var sec in _KvpGroup.SHowyDatas)
                {
                    layout.SetGridWidget(row, column, GetWidget(sec));

                    column++;
                }

                if (_KvpGroup.Cancel)
                {
                    double NewWidth = RowHright - RowHright / 6;

                    Border TakeBorder = new()
                    {
                        Width = NewWidth,
                        Height = NewWidth,
                        Background = "CoralRed".FindSolidBrush(),
                        CornerRadius = new CornerRadius(NewWidth / 2),
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                        Child = new TextBlock()
                        {
                            Text = "\ue61b",
                            FontFamily = "Icon".FindSource<FontFamily>(),
                            FontSize = 20.0,
                            Foreground = "DeepWhite".FindSolidBrush(),
                            Background = Brushes.Transparent,
                            HorizontalAlignment = HorizontalAlignment.Center,
                            VerticalAlignment = VerticalAlignment.Center
                        }
                    };
                    TakeBorder.PreviewMouseUp += Take;
                    layout.SetGridWidget(row, 4, TakeBorder);
                }

            }, DispatcherPriority.Background);
        }

        private void CompleteLoaded(object? sender, RoutedEventArgs e)
        {
            if (sender is not null and KeyValuePairLiBox self)
            {
                self.Ashbin = new Ruined(self, () =>
                {
                    foreach (var kvp in self.SubscriptionKeyvaluePair)
                    {
                        if (kvp.Key is VariantButton _Buttom)
                        {
                            if (_Buttom.Name == "SaveButtom")
                            {
                                _Buttom.PreviewMouseUp -= CapTrue;
                            }
                            else if (_Buttom.Name == "AddButtom")
                            {
                                _Buttom.PreviewMouseUp -= Addtion;
                            }
                            else if (_Buttom.Name == "ExitButton")
                            {
                                _Buttom.PreviewMouseUp -= Exit;
                            }
                        }
                    }
                    self.SubscriptionKeyvaluePair.Clear();
                    self.Ashbin = null;
                });
            }
            Loaded -= CompleteLoaded;
        }

        private readonly object _syncobj = new();

        public bool _disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            Dispatcher.Invoke(() =>
            {
                bool _synclock = false;
                try
                {
                    if (!_disposed)
                    {
                        Monitor.Enter(_syncobj, ref _synclock);

                        _disposed = true;
                    }
                }
                finally
                {
                    Logger.Debug($"{this} -> release, where lock stat {_synclock}");
                    if (_synclock) Monitor.Exit(_syncobj);
                }
            });
        }

        ~KeyValuePairLiBox()
        {
            Dispose(false);
        }

        private void OnLoader(object? sender, RoutedEventArgs e)
        {
            Dispose();
        }
    }

    public class EnjoyToggleButton : ToggleButton
    {
        private readonly ILogger Logger = Log.ForContext<EnjoyToggleButton>();
        public EnjoyToggleButton()
        {
            Style = "ToggleButtonStyle".FindSource<Style>();
            UseLayoutRounding = true;
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            BorderThickness = new Thickness(2);
            base.OnRenderSizeChanged(sizeInfo);
        }

        public CornerRadius CornerRadius
        {
            set { SetValue(CornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        }

        public Brush IsCheckBorderBrush
        {
            set { SetValue(IsCheckBorderBrushProperty, value); }
            get { return (Brush)GetValue(IsCheckBorderBrushProperty); }
        }

        public Brush UnCheckBorderBrush
        {
            set { SetValue(UnCheckBorderBrushProperty, value); }
            get { return (Brush)GetValue(UnCheckBorderBrushProperty); }
        }

        public static readonly DependencyProperty CornerRadiusProperty =
                DependencyProperty.Register(
                nameof(CornerRadius),
                typeof(CornerRadius),
                typeof(EnjoyToggleButton),
                new PropertyMetadata(new CornerRadius(3)));

        public static readonly DependencyProperty IsCheckBorderBrushProperty =
                DependencyProperty.Register(
                nameof(IsCheckBorderBrush),
                typeof(Brush),
                typeof(EnjoyToggleButton),
                new PropertyMetadata("RoyalSignal".FindSolidBrush()));

        public static readonly DependencyProperty UnCheckBorderBrushProperty =
                DependencyProperty.Register(
                nameof(UnCheckBorderBrush),
                typeof(Brush),
                typeof(EnjoyToggleButton),
                new PropertyMetadata("MistyFern".FindSolidBrush()));


    }

    public class EnjoyCombobox : ComboBox
    {
        public EnjoyCombobox()
        {
            Style = "EnjoyCombobox".FindSource<Style>();
            FontFamily = "Consolas".FindSource<FontFamily>();
            Background = "CoffeeIncrease".FindSolidBrush();
            BorderBrush = "FrostedSlate".FindSolidBrush();
            BorderThickness = new Thickness(1);

            WeakEventManager<ComboBox, RoutedEventArgs>.AddHandler(this, nameof(ComboBox.Loaded), LoadedUI);
            WeakEventManager<ComboBox, RoutedEventArgs>.AddHandler(this, nameof(ComboBox.Unloaded), UnLoadedUI);
        }


        public static void DropSelectionChangedEvent(object? sender, SelectionChangedEventArgs e)
        {
            if (sender is not null && sender is EnjoyCombobox self)
            {
                self.Dispatcher.InvokeAsync(() =>
                {
                    self.SelectedItem = self.SelectedValue;
                    if (!self.IsEditable)
                    {
                        self.TextChangeCommand?.Execute(self.SelectedValue);
                    }
                });
            }
        }
        

        public static void LoadedUI(object? sender, RoutedEventArgs e)
        {
            if (sender is not null && sender is EnjoyCombobox self)
            {
                self.Dispatcher.BeginInvoke(() =>
                {
                    WeakEventManager<ComboBox, SelectionChangedEventArgs>.AddHandler(self, nameof(ComboBox.SelectionChanged), DropSelectionChangedEvent);
                    IEnumerable<TextBox> _TextBoxs = self.FindVisualUpObjects<ComboBox, TextBox>().Where(x => x.Name == "PART_EditableTextBox");

                    if (_TextBoxs.Any())
                    {
                        Binding _ConfigBind = new ("Text")
                        {
                            Source = self,
                            Mode = BindingMode.TwoWay,
                            UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                        };
                        _TextBoxs.ElementAt(0).SetBinding(TextProperty, _ConfigBind);
                        WeakEventManager<TextBox, TextChangedEventArgs>.AddHandler(_TextBoxs.ElementAt(0), nameof(TextBox.TextChanged), TextValueChangeEvent);
                    }
                }, DispatcherPriority.Loaded);
            }
        }

        public static void TextValueChangeEvent(object? sender, TextChangedEventArgs e)
        {
            if (sender is not null and TextBox _TextBox)
            {
                if (_TextBox.FindVisualUpObject<EnjoyCombobox>() is not null and EnjoyCombobox self)
                {
                    string BoxContent = _TextBox.Text;
                    self.Text = BoxContent;
                    self.Content = BoxContent;
                    self.TextChangeCommand?.Execute(_TextBox.Text);
                }
            }
        }

        public static void UnLoadedUI(object? sender, RoutedEventArgs e)
        {
            if (sender is not null && sender is EnjoyCombobox self)
            {
                self.SelectionChanged -= DropSelectionChangedEvent;
                IEnumerable<TextBox> _TextBoxs = self.FindVisualUpObjects<ComboBox, TextBox>().Where(x => x.Name == "PART_EditableTextBox");

                if (_TextBoxs.Any())
                {
                    WeakEventManager<TextBox, TextChangedEventArgs>.RemoveHandler(_TextBoxs.ElementAt(0), nameof(TextBox.TextChanged), TextValueChangeEvent);
                }
                WeakEventManager<ComboBox, RoutedEventArgs>.RemoveHandler(self, nameof(ComboBox.Loaded), LoadedUI);
                WeakEventManager<ComboBox, RoutedEventArgs>.RemoveHandler(self, nameof(ComboBox.Unloaded), UnLoadedUI);
            }
        }

        public string Content
        {
            set { SetValue(ContentProperty, value); }
            get { return (string)GetValue(ContentProperty); }
        }

        public static readonly DependencyProperty ContentProperty =
            DependencyProperty.Register(nameof(Content),
                                        typeof(string),
                                        typeof(EnjoyCombobox),
                                        new PropertyMetadata(string.Empty));

        public string ItemTargetAtrribute
        {
            set { SetValue(ItemTargetAtrributeProperty, value); }
            get { return (string)GetValue(ItemTargetAtrributeProperty); }
        }

        public static readonly DependencyProperty ItemTargetAtrributeProperty =
            DependencyProperty.Register(nameof(ItemTargetAtrribute),
                                        typeof(string),
                                        typeof(EnjoyCombobox),
                                        new PropertyMetadata(string.Empty));
        public CornerRadius CornerRadius
        {
            set { SetValue(CornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        }

        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(nameof(CornerRadius),
                                        typeof(CornerRadius),
                                        typeof(EnjoyCombobox),
                                        new PropertyMetadata(new CornerRadius(5)));

        public CornerRadius DropCornerRadius
        {
            set { SetValue(DropCornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(DropCornerRadiusProperty); }
        }

        public static readonly DependencyProperty DropCornerRadiusProperty =
            DependencyProperty.Register(nameof(DropCornerRadius),
                                        typeof(CornerRadius),
                                        typeof(EnjoyCombobox),
                                        new PropertyMetadata(new CornerRadius(5)));

        public double OptionsFontSize
        {
            set { SetValue(OptionsFontSizeProperty, value); }
            get { return (double)GetValue(OptionsFontSizeProperty); }
        }

        public static readonly DependencyProperty OptionsFontSizeProperty =
            DependencyProperty.Register(nameof(OptionsFontSize),
                                        typeof(double),
                                        typeof(EnjoyCombobox),
                                        new PropertyMetadata(15.0));

        public ICommand TextChangeCommand
        {
            set { SetValue(TextChangeCommandProperty, value); }
            get { return (ICommand)GetValue(TextChangeCommandProperty); }
        }

        public static readonly DependencyProperty TextChangeCommandProperty =
            DependencyProperty.Register(nameof(TextChangeCommand),
                                        typeof(ICommand),
                                        typeof(EnjoyCombobox),
                                        new PropertyMetadata(null));

        public HorizontalAlignment ItemAlignMent
        {
            set { SetValue(ItemAlignMentProperty, value); }
            get { return (HorizontalAlignment)GetValue(ItemAlignMentProperty); }
        }

        public static readonly DependencyProperty ItemAlignMentProperty =
            DependencyProperty.Register(nameof(ItemAlignMent),
                                        typeof(HorizontalAlignment),
                                        typeof(EnjoyCombobox),
                                        new PropertyMetadata(HorizontalAlignment.Center));
    }

    public class EnjoyTable : EnjoyWindow
    {
        private enum Unnoticed
        {
            EraseTrace,
            Delete,
            First,
            Previous,
            Next,
            Last
        }
        private readonly ILogger Logger = Log.ForContext<EnjoyTable>();
        private readonly ConditionalWeakTable<FrameworkElement, ConnectFlag> SubscriptionKeyvaluePair = [];
        private long MaxVisibleUnit = 100;
        private long ValidDataCount = 0;
        private readonly IActivityDetetorServer ActivityDetetorServer;
        private readonly IDataBaseServer DataBaseServer;
        private readonly DataGrid DataTable = new();
        private readonly List<string> DataTableSelections = [];
        private readonly ObservableCollection<WorkOrderUnfold> unfoldResponses = [];
        private readonly List<(string, string)> WorkOrderFields = [];
        private readonly Dictionary<string, string> TextChangeMap = [];
        private readonly OrderFilterCondition FilterCondition = new()
        {
            FilterConditions = [ new OrderFilterCondition.Condition()
                                 {
                                    FilterContent = string.Empty,
                                    FilterFieldType = OrderFilterCondition.FieldType.IMEI
                                 }
                               ],
            Filter_isSimpleQuery = false,
            FilterRange = (0, 100)
        };
        private readonly List<(string, string)> Elements =
                [(nameof(Unnoticed.EraseTrace), "清除设备痕迹"),
                 (nameof(Unnoticed.Delete), "清除写号记录"),
                 (nameof(Unnoticed.First), "首列"),
                 (nameof(Unnoticed.Previous), "上一列"),
                 (nameof(Unnoticed.Next), "下一列"),
                 (nameof(Unnoticed.Last), "尾列")];

        //  UI显示名,对象名、组件类型(自定义名称，用于区分)
        private readonly List<(string, string, string)> TopUIItems = [("工单", nameof(OrderFilterCondition.FieldType.ORDER), nameof(EnjoyTextBox)),
                                                                      ("DOID", nameof(OrderFilterCondition.FieldType.DOID), nameof(EnjoyTextBox)),
                                                                      ("IMEI", nameof(OrderFilterCondition.FieldType.IMEI), nameof(EnjoyTextBox)),
                                                                      ("SN",   nameof(OrderFilterCondition.FieldType.SN), nameof(EnjoyTextBox)),
                                                                      ("蓝牙", nameof(OrderFilterCondition.FieldType.BLUE), nameof(EnjoyTextBox)),
                                                                      ("关联所有条件", nameof(OrderFilterCondition.FieldType.RLTALL), nameof(EnjoySwitch))];

        public Action<List<string>>? DisposeEraseTraceCallBack = (imeis) => {};

        public FrameworkElement TopUI()
        {
            Grid TopGrid = new()
            {
                Height = 98,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Center
            };

            TopGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(50) });
            TopGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(50) });

            TopGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            TopGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            TopGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            int RealIndex = 0;
            int ToprowIndex = 0;
            int WrapLineNum = 3;

            foreach (var TopUI in TopUIItems)
            {
                StackPanel TopStackPanel = new()
                {
                    MinWidth = 293,
                    Orientation = Orientation.Horizontal,
                    Margin = new Thickness(1, 10, 1, 3),
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center
                };

                TextBlock HintText = new()
                {
                    Width = 77,
                    Text = TopUI.Item1,
                    Name = TopUI.Item2,
                    Margin = new Thickness(3, 3, 3, 3),
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Right
                };

                UIElement? Element = null;

                if (TopUI.Item3 == nameof(EnjoyTextBox))
                {
                    EnjoyTextBox TextBox = new()
                    {
                        Height = 33,
                        Width = 150,
                        Name = TopUI.Item2,
                        Margin = new Thickness(3, 1, 3, 1),
                        CornerRadius = new CornerRadius(8),
                        BorderBrush = "DeepMatrix".FindSolidBrush(),
                        BorderThickness = new Thickness(1, 1, 1, 1),
                        HorizontalContentAlignment = HorizontalAlignment.Center,
                        VerticalContentAlignment = VerticalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Left
                    };
                    if (!SubscriptionKeyvaluePair.TryGetValue(TextBox, out ConnectFlag? ButtonFlag))
                    {
                        TextBox.TextChanged += FilterTextChangeEvent;
                        SubscriptionKeyvaluePair.Add(TextBox, new ConnectFlag() { IsConnected = true });
                    }
                    Element = TextBox;
                }

                else if (TopUI.Item3 == nameof(EnjoySwitch))
                {
                    EnjoySwitch _switch = new()
                    {
                        GraphicType = EnjoySwitch.GraphicsType.Elipse,
                        Width = 150,
                        Height = 35,
                        Name = TopUI.Item2,
                        Margin = new Thickness(3, 1, 3, 1),
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Center
                    };

                    _switch.SetBinding(
                        EnjoySwitch.IsPriCheckedProperty,
                        new Binding(nameof(IsRltChecked))
                        {
                            Source = this,
                            Mode = BindingMode.TwoWay
                        });

                    if (!SubscriptionKeyvaluePair.TryGetValue(_switch, out ConnectFlag? SwitchFlag))
                    {
                        _switch.PreviewMouseUp += ReLoadInFilter;
                        SubscriptionKeyvaluePair.Add(_switch, new ConnectFlag() { IsConnected = true });
                    }

                    Element = _switch;
                }

                TextBlock SearchIco = new()
                {
                    Text = "\ue6a2",
                    FontSize = 18,
                    Name = TopUI.Item2,
                    FontWeight = FontWeight.FromOpenTypeWeight(500),
                    Background = Brushes.Transparent,
                    Foreground = "MistyFern".FindSolidBrush(),
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                };

                Border Search = new()
                {
                    Height = 22,
                    Width = 22,
                    Name = TopUI.Item2,
                    Margin = new Thickness(5, 3, 5, 3),
                    CornerRadius = new CornerRadius(14),
                    Background = "JadeFlow".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Child = SearchIco
                };

                TopStackPanel.Children.Add(HintText);
                TopStackPanel.Children.Add(Element);
                TopStackPanel.Children.Add(Search);

                if (RealIndex % WrapLineNum == 0 && RealIndex != 0)
                {
                    RealIndex = 0;
                    ToprowIndex++;
                }
                TopGrid.SetGridWidget(ToprowIndex, RealIndex, TopStackPanel);
                RealIndex++;

                if (!SubscriptionKeyvaluePair.TryGetValue(Search, out ConnectFlag? BorderFlag))
                {
                    Search.PreviewMouseUp += ReLoadInFilter;
                    SubscriptionKeyvaluePair.Add(Search, new ConnectFlag() { IsConnected = true });
                }
            }
            return TopGrid;
        }

        public FrameworkElement BottonUI()
        {
            UniformGrid BottonGrid = new()
            {
                Columns = Elements.Count + 2
            };

            TextBlock QueryUnitCount = new()
            {
                Name = "QueryUnitCount",
                Foreground = "StormyHarbor".FindSolidBrush(),
                Margin = new Thickness(10, 0, 10, 0),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center
            };
            BindingOperations.SetBinding(
                QueryUnitCount,
                TextBlock.TextProperty,
                new Binding("QueryDataCount")
                {
                    Source = this,
                    Mode = BindingMode.OneWay
                });
            BottonGrid.Children.Add(QueryUnitCount);

            foreach (var tuple in Elements)
            {
                VariantButton FuncButton = new()
                {
                    Height = 26,
                    Width = 110,
                    Name = tuple.Item1,
                    Content = tuple.Item2,
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center
                };
                BottonGrid.Children.Add(FuncButton);
                if (!SubscriptionKeyvaluePair.TryGetValue(FuncButton, out ConnectFlag? ButtonFlag))
                {
                    FuncButton.PreviewMouseUp += PageChange;
                    SubscriptionKeyvaluePair.Add(FuncButton, new ConnectFlag() { IsConnected = true });
                }
                if (!SubscriptionKeyvaluePair.TryGetValue(QueryUnitCount, out ConnectFlag? CountFlag))
                {
                    SubscriptionKeyvaluePair.Add(QueryUnitCount, new ConnectFlag() { IsConnected = true });
                }
            }

            //  --- append
            StackPanel MaxUnitPanel = new()
            {
                Orientation = Orientation.Horizontal,
                Height = 30,
                MinWidth = 230,
                Margin = new Thickness(10, 0, 10, 0),
            };

            TextBlock MaxUnitHint = new()
            {
                Text = "最大显示条目",
                VerticalAlignment = VerticalAlignment.Center
            };

            ComboBox MaxUnitComboBox = new()
            {
                ItemsSource = new List<int>() { 50, 100, 150, 200, 250, 300 },
                Height = 30,
                Text = "100",
                Margin = new Thickness(5, 0, 0, 0),
                Name = "MaxUnit",
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalContentAlignment = VerticalAlignment.Center,
                HorizontalContentAlignment = HorizontalAlignment.Center
            };

            MaxUnitPanel.Children.Add(MaxUnitHint);
            MaxUnitPanel.Children.Add(MaxUnitComboBox);

            if (!SubscriptionKeyvaluePair.TryGetValue(MaxUnitComboBox, out ConnectFlag? ComboBoxFlag))
            {
                MaxUnitComboBox.SelectionChanged += MaxComboBoxEvent;
                SubscriptionKeyvaluePair.Add(MaxUnitComboBox, new ConnectFlag() { IsConnected = true });
            }

            BottonGrid.Children.Add(MaxUnitPanel);
          
            return BottonGrid;
        }

        public EnjoyTable()
        {
            FontFamily = "Consolas".FindSource<FontFamily>();
 
            App MyApp = (App)Application.Current;
            this.TitleNamed = "工单预览";
            this.TitleIcon = "\ue631";
            this.Topmost = false;
            Owner = Application.Current.MainWindow;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            ActivityDetetorServer = MyApp.ServiceProvider.GetRequiredService<IActivityDetetorServer>();
            DataBaseServer = MyApp.ServiceProvider.GetRequiredService<IDataBaseServer>();

            FilterCondition.FilterRange = (0, MaxVisibleUnit);
            DataTable.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
            DataTable.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
            DataTable.AutoGenerateColumns = false;
            DataTable.EnableRowVirtualization = true;
            DataTable.EnableColumnVirtualization = true;
            DataTable.SetValue(VirtualizingStackPanel.IsVirtualizingProperty, true);
            DataTable.SetValue(VirtualizingStackPanel.VirtualizationModeProperty, VirtualizationMode.Recycling);
            DataTable.SetValue(ScrollViewer.CanContentScrollProperty, true);
            DataTable.RowBackground = "DeepWhite".FindSolidBrush();
            DataTable.UseLayoutRounding = true;
            DataTable.CanUserAddRows = false;
            DataTable.RowHeight = 27;
            DataTable.ColumnWidth = DataGridLength.Auto;

            DataTable.CellStyle = "TableGridCell".FindSource<Style>();
            DataTable.Style = "TableGrid".FindSource<Style>();
            DataTable.ColumnHeaderStyle = "TableGridColumnHead".FindSource<Style>();
            DataTable.RowStyle = "TableGridRow".FindSource<Style>();

            Loaded += CompleteLoaded;
            Unloaded += DistoryLoad;

            DataTable.LoadingRow += RowUpdate;
            DataTable.SelectionChanged += SelectionChangeEvent;
        }

        ~EnjoyTable()
        {
            Logger.Print(RuntimeLog.LogType.Warning, "Finalized");
        }

        public void SelectionChangeEvent(object sender, SelectionChangedEventArgs e)
        {
            DataTableSelections.Clear();
            foreach (var workorder in DataTable.SelectedItems)
            {
                if (workorder is not null and WorkOrderUnfold _OrderUnfold)
                {
                    DataTableSelections.Add(_OrderUnfold.Imei);
                }
            }
        }

        private void RowUpdate(object? sender, DataGridRowEventArgs DataGrid)
        {
            DataGrid.Row.Header = (DataGrid.Row.GetIndex() + 1).ToString();
        }

        private async void CompleteLoaded (object sender, RoutedEventArgs e)
        {
            Grid MainGrid = new()
            {
                UseLayoutRounding = true,
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch,
            };

            MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(100) });
            MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(37) });
            MainGrid.SetGridWidget(0, 0, TopUI());
            MainGrid.SetGridWidget(1, 0, DataTable);
            MainGrid.SetGridWidget(2, 0, BottonUI());

            MainContent = MainGrid;

            await Load(FilterCondition);
            Loaded -= CompleteLoaded;
            Logger.Print(RuntimeLog.LogType.Debug, "loaded acton execute complete");
        }

        private async void DistoryLoad(object sender, RoutedEventArgs e)
        {
            foreach (var subcript in SubscriptionKeyvaluePair)
            {
                string Name = subcript.Key.Name;

                if (subcript.Key is ComboBox _ComboBox && subcript.Value.IsConnected &&
                    Name == "MaxUnit")
                {
                    _ComboBox.SelectionChanged -= MaxComboBoxEvent;
                }
                else if (subcript.Key is TextBox _TextBox && subcript.Value.IsConnected &&
                         TopUIItems.Select(x=>x.Item2).Contains(Name))
                {
                    _TextBox.TextChanged -= FilterTextChangeEvent;
                }
                else if (subcript.Key is Border _Border && subcript.Value.IsConnected &&
                         TopUIItems.Select(x => x.Item2).Contains(Name))
                {
                    _Border.PreviewMouseUp -= ReLoadInFilter;
                }
                else if (subcript.Key is VariantButton _Button && subcript.Value.IsConnected &&
                         Elements.Select(x=>x.Item1).Contains(Name))
                {
                    _Button.PreviewMouseUp -= PageChange;
                }
                else if (subcript.Key is EnjoySwitch _switch && subcript.Value.IsConnected && 
                         TopUIItems.Last().Item2 == Name)
                {
                    BindingOperations.ClearBinding(_switch, EnjoySwitch.IsPriCheckedProperty);
                }
                else if (subcript.Key is TextBlock _counth && subcript.Value.IsConnected &&
                         Name == "QueryUnitCount")
                {
                    BindingOperations.ClearBinding(_counth, QueryDataCountProperty);
                }
            }

            DataTable.Style = null;
            DataTable.CellStyle = null;
            DataTable.ColumnHeaderStyle = null;
            DataTable.RowStyle = null;
            SubscriptionKeyvaluePair.Clear();
            BindingOperations.ClearAllBindings(DataTable);
            // 强制清理 DataGrid 内部状态
            DataTable.UnselectAll();
            DataTable.SelectedItems.Clear();
            DataTable.ItemsSource = null;
            DataTable.LoadingRow -= RowUpdate;
            DataTable.SelectionChanged -= SelectionChangeEvent;

            DisposeEraseTraceCallBack = null;
            FilterCondition.FilterConditions.Clear();
            Unloaded -= DistoryLoad;

            await Task.Delay(2000);

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            Logger.Print(RuntimeLog.LogType.Debug, "order table clear finish");
        }

        private void FilterTextChangeEvent(object sender, TextChangedEventArgs e)
        {
            if (sender is TextBox _TextBox)
            {
                if (TextChangeMap.ContainsKey(_TextBox.Name))
                {
                    TextChangeMap[_TextBox.Name] = _TextBox.Text;
                }
                else
                {
                    TextChangeMap.TryAdd(_TextBox.Name, _TextBox.Text);
                }
            }
        }

        public async Task Load(OrderFilterCondition Conditions)
        {
            object? result = await ActivityDetetorServer.AutoFindDim(Conditions);

            void SetDataGridHead(ICollection<WorkOrderUnfold> unfoldResponses)
            {
                WorkOrderFields.Clear();

                foreach (var model in unfoldResponses)
                {
                    foreach (var property in model.GetPropertys(1))
                    {

                        if (ActivityAssistBehivor.Behivor.DBReserveDutyTranslationMap.TryGetValue(property.Name, out string? m_tranlation))
                        {
                            if (!WorkOrderFields.Any(x => x.Item1 == property.Name))
                            {
                                WorkOrderFields.Add((property.Name, m_tranlation));
                            }
                        }
                        else if (ActivityAssistBehivor.Behivor.DBPreviewTranslationMap.TryGetValue(property.Name, out string? s_tranlation))
                        {
                            if (!WorkOrderFields.Any(x => x.Item1 == property.Name))
                            {
                                WorkOrderFields.Add((property.Name, s_tranlation));
                            }
                        }
                    }
                }

                DataTable.Columns.Clear();

                foreach (var info in WorkOrderFields)
                {
                    if (!DataTable.Columns.Any(x => x.Header.GetSafetyChar() == info.Item2))
                    {
                        DataTable.Columns.Add(new DataGridTextColumn
                        {
                            Header = info.Item2,
                            Binding = new Binding(info.Item1),
                            Width = DataGridLength.Auto
                        });
                    }
                }
            }

            if (DataTable.Items.Count > 0)
            {
                DataTable.ItemsSource = null;
            }

            if (result is not null and Supabase.Postgrest.Responses.ModeledResponse<WorkOrderUnfold> unfoldResponse && unfoldResponse.Models.Count > 0)
            {
                unfoldResponses.Clear();

                unfoldResponses.AddRange(unfoldResponse.Models);

                SetDataGridHead(unfoldResponses);

                if (DataBaseServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                {
                    Supabase.Interfaces.ISupabaseTable<WorkOrderUnfold, Supabase.Realtime.RealtimeChannel>? CloudQuery = ActivityDetetorServer.GetCloudFilterQuery(FilterCondition.FilterConditions);

                    if (CloudQuery != null)
                    {
                        long DataCount = await CloudQuery.Count(Supabase.Postgrest.Constants.CountType.Exact);
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            ValidDataCount = DataCount;
                            QueryDataCount = $"共 {ValidDataCount.GetSafetyChar()} 条数据";
                        });
                    }
                }
            }
            else if (result is not null and Dictionary<string, ICollection<object>> unfoldQuery)
            {
                Dictionary<PropertyInfo, ICollection<string>> Classify = [];

                foreach (var kvp in unfoldQuery)
                {
                    WorkOrderUnfold workOrder = new ();

                    PropertyInfo? CurrentProperty = null;

                    foreach (PropertyInfo property in workOrder.GetPropertys(2))
                    {
                        if (property.GetCustomAttribute<ColumnAttribute>() is not null and ColumnAttribute _Column &&
                            _Column.ColumnName == kvp.Key)
                        {
                            CurrentProperty = property;
                            break;
                        }
                    }
                        
                    if (CurrentProperty != null)
                    {
                        if (unfoldResponses.Count == 0)
                        {
                            foreach(var _value in kvp.Value)
                            {
                                WorkOrderUnfold template = new();
                                CurrentProperty.SetValue(template, _value.GetSafetyChar());
                                unfoldResponses.Add(template);
                            }
                        }
                        else
                        {
                            int index = 0;
                            foreach (var _value in kvp.Value)
                            {
                                CurrentProperty.SetValue(unfoldResponses.ElementAt(index), _value.GetSafetyChar());
                                index++;
                            }
                        }
                    }
                }
                    
                SqliteExceuteResult localresult = await DataBaseServer.LocalDBQueryFree(ActivityDetetorServer.GetLocalFilterQuerySql(FilterCondition.FilterConditions, 2));

                if (localresult.ScalarNumber is not null and long _scalar)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ValidDataCount = _scalar;
                        QueryDataCount = $"共 {ValidDataCount.GetSafetyChar()} 条数据";
                    });
                }
            }
            if (unfoldResponses.Count > 0)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    SetDataGridHead(unfoldResponses);
                    DataTable.ItemsSource = unfoldResponses;
                });
            }
            Logger.Print(RuntimeLog.LogType.Debug, "load acton execute finish");
      
        }

        private async void PageChange(object sender, MouseButtonEventArgs e)
        {
            if (sender is VariantButton button && FilterCondition.FilterRange is not null)
            {
                long start = FilterCondition.FilterRange.Value.Item1;
                long end = FilterCondition.FilterRange.Value.Item2;
                switch (button.Name)
                {
                    case nameof(Unnoticed.EraseTrace):
                        if (DataBaseServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud)
                        {
                            if (DataBaseServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                            {
                                await DataBaseServer.CloudAnchorChannel<WorkOrderUnfold>(
                                () =>
                                {
                                    if (DataTableSelections.DeepCopy() is not null and List<string> _DataTableSelections)
                                    {
                                        DisposeEraseTraceCallBack?.Invoke(_DataTableSelections);
                                    }
                                    Logger.Print(RuntimeLog.LogType.Debug, "read write clear action completed");
                                },
                                async () =>
                                {
                                    await CloudDB.From<WorkOrderUnfold>()
                                      .Filter("imei", Supabase.Postgrest.Constants.Operator.In, DataTableSelections)
                                      .Set(x => x.UsingTime, string.Empty)
                                      .Set(x => x.VerifyTime, string.Empty)
                                      .Update();
                                },
                                async () =>
                                {
                                    await CustomMessageBox.Show(
                                        new CustomMessageBox.InquiryNmPopupSetting
                                        {
                                            Msg_Title = "异常",
                                            Msg_InquiryIcon = 1,
                                            Msg_InquiryButtoms = ["确定"],
                                            Msg_BodyText = "清除操作异常"
                                        });
                                });
                            }
                        }
                        else if (DataBaseServer.GetDBIdentify() == DB.DB_TYPE.DB_Local)
                        {
                            string DeleteWRrecordSql = $"UPDATE workorder_unfold SET using_time='', verify_time='' WHERE imei in ({DataTableSelections.Join(",", true)})";
                            
                            await DataBaseServer.LocalDBQueryFree(DeleteWRrecordSql);

                            if (DataTableSelections.DeepCopy() is not null and List<string> _DataTableSelections)
                            {
                                DisposeEraseTraceCallBack?.Invoke(_DataTableSelections);
                            }
                        }
                        break;

                    case nameof(Unnoticed.Delete):
                        try
                        {
                            if (DataBaseServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud)
                            {
                                if (DataBaseServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                                {
                                    await DataBaseServer.CloudAnchorChannel<WorkOrderUnfold>(
                                    () =>
                                    {
                                        Logger.Print(RuntimeLog.LogType.Debug, "read write clear action completed");
                                    },
                                    async () =>
                                    {
                                        await CloudDB.From<WorkOrderUnfold>()
                                          .Filter("imei", Supabase.Postgrest.Constants.Operator.In, DataTableSelections)
                                          .Set(x => x.UsingTime, string.Empty)
                                          .Set(x => x.VerifyTime, string.Empty)
                                          .Update();
                                    },
                                    async () =>
                                    {
                                        await CustomMessageBox.Show(new CustomMessageBox.InquiryNmPopupSetting { 
                                            Msg_Title = "异常", 
                                            Msg_InquiryIcon = 1, 
                                            Msg_BodyText = "清除操作异常", 
                                            Msg_InquiryButtoms = ["确定"] });
                                    });
                                }
                            }
                            else if (DataBaseServer.GetDBIdentify() == DB.DB_TYPE.DB_Local)
                            {
                                string DeleteWRrecordSql = $"UPDATE workorder_unfold SET using_time='', verify_time='' WHERE imei in ({DataTableSelections.Join(",", true)})";
                                await DataBaseServer.LocalDBQueryFree(DeleteWRrecordSql);
                            }
                        } 
                        catch (Exception error)
                        {
                            Serilog.Log.Logger.Print(RuntimeLog.LogType.Error, $"PageChange - Delete {error.Message}");
                        }
                        break;

                    case nameof(Unnoticed.First):
                        FilterCondition.FilterRange = (0, MaxVisibleUnit);
                        break;

                    case nameof(Unnoticed.Previous):
                        if (start - MaxVisibleUnit >= 0)
                        {
                            FilterCondition.FilterRange = (start - MaxVisibleUnit, end - MaxVisibleUnit);
                        }
                        else
                        {
                            FilterCondition.FilterRange = (0, MaxVisibleUnit);
                        }
                        break;

                    case nameof(Unnoticed.Next):

                        if (end + MaxVisibleUnit < ValidDataCount)
                        {
                            FilterCondition.FilterRange = (start + MaxVisibleUnit, end + MaxVisibleUnit);

                        }
                        else
                        {
                            FilterCondition.FilterRange = (end, ValidDataCount);
                        }

                        break;

                    case nameof(Unnoticed.Last):
                        if (ValidDataCount < MaxVisibleUnit)
                        {
                            FilterCondition.FilterRange = (0, ValidDataCount);
                        }
                        else
                        {
                            FilterCondition.FilterRange = (ValidDataCount - MaxVisibleUnit, ValidDataCount);
                        }
                        break;
                }
                await Load(FilterCondition);
            }
        }

        private async void ReLoadInFilter(object sender, MouseButtonEventArgs e)
        {
            if (sender is Border _Border)
            {
                OrderFilterCondition.FieldType CurrentFieldType = ActivityDetetorServer.GetWorkOrderFieldType(_Border.Name);

                if (CurrentFieldType == OrderFilterCondition.FieldType.RLTALL && IsRltChecked)
                {
                    List<OrderFilterCondition.Condition> _conditions = [];

                    foreach(var _any in TextChangeMap)
                    {
                        _conditions.Add(new OrderFilterCondition.Condition()
                        {
                            FilterContent = _any.Value,
                            FilterFieldType = ActivityDetetorServer.GetWorkOrderFieldType(_any.Key)
                        });
                    }

                    if (FilterCondition.FilterRange != null) //  避免跨度太大导致数据不显示的问题
                    {
                        FilterCondition.FilterRange = (0, FilterCondition.FilterRange.Value.Item2);
                    }

                    FilterCondition.FilterConditions = _conditions;

                    await Load(FilterCondition);
                }
                else
                {
                    if (TextChangeMap.TryGetValue(_Border.Name, out string? content))
                    {
                        Log.Logger.Print(RuntimeLog.LogType.Debug, $"field: {CurrentFieldType} uielement name: {_Border.Name} filter content: {content}");

                        FilterCondition.FilterConditions = [ new OrderFilterCondition.Condition()
                        {
                            FilterContent = content,
                            FilterFieldType = CurrentFieldType
                        }];
                        await Load(FilterCondition);
                    }
                }
            }
        }

        private async void MaxComboBoxEvent(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox ComBox && FilterCondition.FilterRange is not null)
            {
                long start = FilterCondition.FilterRange.Value.Item1;
                string selection = ComBox.SelectedValue.GetSafetyChar(IsSealed);
                if (int.TryParse(selection, out int _MaxVisibleUnit))
                {
                    MaxVisibleUnit = _MaxVisibleUnit;

                    if (start + MaxVisibleUnit > ValidDataCount)
                    {
                        FilterCondition.FilterRange = (start - MaxVisibleUnit, ValidDataCount);
                    }
                    else
                    {
                        FilterCondition.FilterRange = (start, start + MaxVisibleUnit);
                    }
                    await Load(FilterCondition);
                }
            }
        }

        // 全选标识  relation all ，关联所有条件
        public bool IsRltChecked
        {
            get => (bool)GetValue(IsRltCheckedProperty);
            set => SetValue(IsRltCheckedProperty, value);
        }

        public string QueryDataCount
        {
            get => (string)GetValue(QueryDataCountProperty);
            set => SetValue(QueryDataCountProperty, value);
        }


        private static readonly DependencyProperty IsRltCheckedProperty = DependencyProperty.Register(
            nameof(IsRltChecked),
            typeof(bool),
            typeof(EnjoyTable),
            new PropertyMetadata(false));

        private static readonly DependencyProperty QueryDataCountProperty = DependencyProperty.Register(
            nameof(QueryDataCount),
            typeof(string),
            typeof(EnjoyTable));
    }

    public class EnjoySwitch : ToggleButton
    {
        public enum GraphicsType
        {
            Elipse,
            Rect
        }

        private static readonly ILogger Logger = Log.ForContext<EnjoySwitch>();

        public EnjoySwitch()
        {
            Width = 160;
            Height = 60;
            Background = "DeepWhite".FindSolidBrush();

            Checked += DoCheckedEvent;
            Unchecked += NoCheckedEvent;
            Unloaded += NoLoaded;
        }

        private void DoCheckedEvent(object sender, RoutedEventArgs e)
        {
            IsPriChecked = true;
        }

        private void NoCheckedEvent(object sender, RoutedEventArgs e)
        {
            IsPriChecked = false;
        }

        private void NoLoaded(object sender, RoutedEventArgs e)
        {
            Checked -= DoCheckedEvent;
            Unchecked -= DoCheckedEvent;
            Unloaded -= NoLoaded;
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo info)
        {
            TypeUpdate(GraphicType);
        }

        private void StateUpdate(bool update)
        {
            Dispatcher.InvokeAsync(() =>
            {
                if (update)
                {
                    GraphicABackColor = GraphicCBackColor;
                    HorizontalAlign = HorizontalAlignment.Right;
                }
                else
                {
                    GraphicABackColor = GraphicDBackColor;
                    HorizontalAlign = HorizontalAlignment.Left;
                }
            });
        }

        private void TypeUpdate(GraphicsType Type)
        {
            if (Type == GraphicsType.Elipse)
            {
                GraphicRadius = new CornerRadius(Height / 2);
                GraphicWidth = Height - GraphicBorderThickness.Top - GraphicBorderThickness.Bottom;
                GraphicHeight = Height - GraphicBorderThickness.Top - GraphicBorderThickness.Bottom;
            }
            else
            {
                GraphicRadius = new CornerRadius(8);
            }
        }

        private static void GraphicTypeChangeEvent(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is GraphicsType _Type && 
                sender is EnjoySwitch self)
            {
                self.TypeUpdate(_Type);
            }
        }

        private static void IsCheckedChangeEvent(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is bool isChecked && sender is EnjoySwitch self)
            {
                self.StateUpdate(isChecked);
            }
        }

        public bool IsPriChecked
        {
            set { SetValue(IsPriCheckedProperty, value); }
            get { return (bool)GetValue(IsPriCheckedProperty); }
        }

        public CornerRadius CornerRadius
        {
            set { SetValue(CornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        }

        public Thickness GraphicBorderThickness
        {
            set { SetValue(GraphicBorderThicknessProperty, value); }
            get { return (Thickness)GetValue(GraphicBorderThicknessProperty); }
        }

        public HorizontalAlignment HorizontalAlign
        {
            set { SetValue(HorizontalAlignProperty, value); }
            get { return (HorizontalAlignment)GetValue(HorizontalAlignProperty); }
        }

        public Brush GraphicABackColor
        {
            set { SetValue(GraphicABackColorProperty, value); }
            get { return (Brush)GetValue(GraphicABackColorProperty); }
        }

        public Brush GraphicDBackColor
        {
            set { SetValue(GraphicDBackColorProperty, value); }
            get { return (Brush)GetValue(GraphicDBackColorProperty); }
        }

        public Brush GraphicCBackColor
        {
            set { SetValue(GraphicCBackColorProperty, value); }
            get { return (Brush)GetValue(GraphicCBackColorProperty); }
        }

        public double GraphicWidth
        {
            set { SetValue(GraphicWidthProperty, value); }
            get { return (double)GetValue(GraphicWidthProperty); }
        }

        public double GraphicHeight
        {
            set { SetValue(GraphicHeightProperty, value); }
            get { return (double)GetValue(GraphicHeightProperty); }
        }

        public CornerRadius GraphicRadius
        {
            set { SetValue(GraphicRadiusProperty, value); }
            get { return (CornerRadius)GetValue(GraphicRadiusProperty); }
        }

        public GraphicsType GraphicType
        {
            set { SetValue(GraphicTypeProperty, value); }
            get { return (GraphicsType)GetValue(GraphicTypeProperty); }
        }

        public static readonly DependencyProperty IsPriCheckedProperty =
            DependencyProperty.Register(
                nameof(IsPriChecked),
                typeof(bool),
                typeof(EnjoySwitch),
                new PropertyMetadata(IsCheckedChangeEvent));

        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(
                nameof(CornerRadius),
                typeof(CornerRadius),
                typeof(EnjoySwitch),
                new PropertyMetadata(new CornerRadius(4)));

        public static readonly DependencyProperty GraphicBorderThicknessProperty =
            DependencyProperty.Register(
                nameof(GraphicBorderThickness),
                typeof(Thickness),
                typeof(EnjoySwitch),
                new PropertyMetadata(new Thickness(2)));

        public static readonly DependencyProperty HorizontalAlignProperty =
            DependencyProperty.Register(
                nameof(HorizontalAlign),
                typeof(HorizontalAlignment),
                typeof(EnjoySwitch),
                new PropertyMetadata(HorizontalAlignment.Left));

        public static readonly DependencyProperty GraphicABackColorProperty =
            DependencyProperty.Register(
                nameof(GraphicABackColor),
                typeof(Brush),
                typeof(EnjoySwitch),
                new PropertyMetadata("SunsetCoral".FindSolidBrush()));

        public static readonly DependencyProperty GraphicDBackColorProperty =
            DependencyProperty.Register(
                nameof(GraphicDBackColor),
                typeof(Brush),
                typeof(EnjoySwitch),
                new PropertyMetadata("SunsetCoral".FindSolidBrush()));

        public static readonly DependencyProperty GraphicCBackColorProperty =
            DependencyProperty.Register(
                nameof(GraphicCBackColor),
                typeof(Brush),
                typeof(EnjoySwitch),
                new PropertyMetadata("JadeFlow".FindSolidBrush()));

        public static readonly DependencyProperty GraphicWidthProperty =
            DependencyProperty.Register(
                nameof(GraphicWidth),
                typeof(double),
                typeof(EnjoySwitch),
                new PropertyMetadata(60.0));

        public static readonly DependencyProperty GraphicHeightProperty =
            DependencyProperty.Register(
                nameof(GraphicHeight),
                typeof(double),
                typeof(EnjoySwitch),
                new PropertyMetadata(60.0));

        public static readonly DependencyProperty GraphicRadiusProperty =
            DependencyProperty.Register(
                nameof(GraphicRadius),
                typeof(CornerRadius),
                typeof(EnjoySwitch),
                new PropertyMetadata(new CornerRadius(8)));

        public static readonly DependencyProperty GraphicTypeProperty =
            DependencyProperty.Register(
                nameof(GraphicType),
                typeof(GraphicsType),
                typeof(EnjoySwitch),
                new PropertyMetadata(GraphicsType.Rect, GraphicTypeChangeEvent));
    }

    public class EnjoySlider : Slider
    {
        public EnjoySlider()
        {
            Style = "CapacitySlider".FindSource<Style>();
        }
    }

    public class EnjoyContentPopue : Window, IDisposable
    {
        EnjoyRichTextBox? TextBox = null;

        public class InfoPakage
        {
            public double Location_X = -1;

            public double Location_Y = -1;

            public double Win_Width = 300;

            public double Win_Height = 160;

            public IEnumerable<object> Contents = [];

        }

        public ObservableCollection<object> DynamicRichContent { set; get; } = [];

        public EnjoyContentPopue(InfoPakage Ifpakage)
        {
            if (Ifpakage.Location_X != -1 && Ifpakage.Location_Y != -1)
            {
                WindowStartupLocation = WindowStartupLocation.Manual;
                Left = Ifpakage.Location_X; 
                Top = Ifpakage.Location_Y;
            }
            else
            {
                Window win = Application.Current.MainWindow;
                Left = win.Left + win.Width;
                Top = win.Top;
            }

            Width = Ifpakage.Win_Width;

            Height = Ifpakage.Win_Height;

            WindowStyle = WindowStyle.None;

            WindowChrome Mtchrome = new ()
            {
                CornerRadius = new CornerRadius(6),
                ResizeBorderThickness = new Thickness(1)
            };

            WindowChrome.SetWindowChrome(this, Mtchrome);

            ShowContent(Ifpakage.Contents);
        }

        private void ShowContent(IEnumerable<object> Contents)
        {
            this.Dispatcher.InvokeAsync(() =>
            {
                TextBox = new()
                {
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    CornerRadius = new CornerRadius(6),
                    BorderBrush = "FrostedSlate".FindSolidBrush(),
                    BorderThickness = new Thickness(1),
                    Style = "RichTextBox".FindSource<Style>(),
                    Background = "MoonlitLavender".FindSolidBrush(),
                    IsReadOnly = true,
                    DymanicContentCollection = DynamicRichContent
                };

                DynamicRichContent.AddRange(Contents);

                AddChild(TextBox);

                Show();
            });
        }

        protected override void OnMouseLeave(MouseEventArgs e)
        {
            Dispose();
            base.OnMouseLeave(e);
        }

        public void Dispose()
        {
            this.Dispatcher.InvokeAsync(() =>
            {
                Close();
            });
            GC.SuppressFinalize(this);
        }
    }

    public class EnjoyRuntimeLog : EnjoyWindow, IDisposable
    {
        public Action<List<object>>? ClosedCallBack = null;

        private readonly ILogger Logger = Log.ForContext<EnjoyRuntimeLog>();

        public ObservableCollection<object> DynamicRichContent { set; get; } = [];

        public EnjoyRuntimeLog()
        {
            Width = 750;

            Height = 350;

            TitleIcon = "\ue627";

            TitleNamed = "日志窗口";

            BorderBrush = "PineTrail".FindSolidBrush();

            Closed += Distory;
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == OpacityProperty)
            {
                if (e.NewValue is double _NOpacity && _NOpacity == 0 &&
                    e.OldValue is double _OOpacity && _OOpacity > 0 && _OOpacity < 1)
                {
                    Close();
                    Logger.Print(RuntimeLog.LogType.Warning, "log face is close");
                }
            }
            base.OnPropertyChanged(e);
        }

        public void Showy()
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                EnjoyRichTextBox TextBox = new()
                {
                    Name = "LogRichBox",
                    ScrollToEndKey = Key.None,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    CornerRadius = new CornerRadius(6),
                    FontSize = 13,
                    FontFamily = "Consolas".FindSource<FontFamily>(),
                    BorderBrush = "FrostedSlate".FindSolidBrush(),
                    BorderThickness = new Thickness(1),
                    Style = "RichTextBox".FindSource<Style>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    Background = Brushes.Transparent,
                    IsReadOnly = true,
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto
                };

                MainContent = TextBox;

                Binding RichboxBinding = new()
                {
                    Source = DynamicRichContent,
                    Mode = BindingMode.OneWay,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                };

                TextBox.SetBinding(EnjoyRichTextBox.DymanicContentCollectionProperty, RichboxBinding);

                Show();
                Application.Current.MainWindow.Activate();
                Application.Current.MainWindow.Topmost = true;
                Application.Current.MainWindow.Topmost = false;
                Application.Current.MainWindow.Focus();

                DoubleAnimation VisibleAnimation = new(1.0, new Duration(TimeSpan.FromMilliseconds(400)));

                BeginAnimation(OpacityProperty, VisibleAnimation);

                Logger.Print(RuntimeLog.LogType.Debug, "log face is completed loader");
            });
        }

        public void UpdateLocation(double x, double y)
        {
            this.Dispatcher.Invoke(() =>
            {
                WindowStartupLocation = WindowStartupLocation.Manual;
                Left = x;
                Top = y;
            });
        }

        public void AddContent(object content)
        {
            this.Dispatcher.Invoke(() =>
            {
                if (DynamicRichContent is null && content is EnjoyRichTextBox.Text _Text)
                {
                    Logger.Print(RuntimeLog.LogType.Fatal, $" DynamicRichContent object is destory, continue echo this content {_Text.Contnet}");
                }
                
                else
                {
                    DynamicRichContent?.Add(content);
                }
            });
        }

        private void Distory(object? sender, EventArgs e)
        {
            ClosedCallBack?.Invoke([..DynamicRichContent]);
            Closed -= Distory;
        }

        public void Dispose()
        {
            this.Dispatcher.Invoke(() =>
            {
                DoubleAnimation CloseAnimation = new(0, new Duration(TimeSpan.FromMilliseconds(300)));

                this.BeginAnimation(OpacityProperty, CloseAnimation);

                DynamicRichContent.Clear();

                Logger.Print(RuntimeLog.LogType.Warning, "log face is release");
            });
            GC.SuppressFinalize(this);
        }
    }
}
